不在对象上下文中时使用$this的PHP无脂肪框架?

不在对象上下文中时使用$this的PHP无脂肪框架?,php,model-view-controller,pdo,fat-free-framework,Php,Model View Controller,Pdo,Fat Free Framework,我正在开发一个项目使用。在文档中,他们说您可以为项目构建自己的框架,因此我的项目目录如下所示: // Kickstart the framework $f3=require($_SERVER['DOCUMENT_ROOT'] . '/project_name/lib/base.php'); $f3->set('AUTOLOAD',''.$_SERVER['DOCUMENT_ROOT'] . '/project_name/controllers/; '.$_SERVER['DOCUMENT_

我正在开发一个项目使用。在文档中,他们说您可以为项目构建自己的框架,因此我的项目目录如下所示:

// Kickstart the framework
$f3=require($_SERVER['DOCUMENT_ROOT'] . '/project_name/lib/base.php');
$f3->set('AUTOLOAD',''.$_SERVER['DOCUMENT_ROOT'] . '/project_name/controllers/; '.$_SERVER['DOCUMENT_ROOT'] . '/project_name/models/');

$f3->set('DEBUG',3);
if ((float)PCRE_VERSION<7.9){
    trigger_error('PCRE version is out of date');
}

if (!($f3->get('DEBUG')))
{
    $f3->set('ONERROR',
        function($f3) {
                $f3->reroute('/');
        }
    );
}

/****************** Start Routing the URLs ******************/

/****** Home Controller ******/
$f3->route('GET|HEAD /',
    function($f3) {
        $f3->reroute('/home');
    }
);

$f3->route('GET|HEAD /index',
    function($f3) {
        $f3->reroute('/home');
    }
);

$f3->route('GET /home','Controller_Home->main');

$f3->run();
class Model
{
    public $f3, $db;

    public function connect()
    {   
        global $db;

        $username = 'username';
        $password = 'password';
        $hostname = 'hostname';
        $dbname = 'dbname';

        try{
            $db = new PDO("mysql:host=$hostname;dbname=$dbname", $username, $password);
            $db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
        }
        catch(PDOException $e){
            echo $e->getMessage();
        }
        print_r($db); // this will give PDO Object ( )
        $this->db = $db;
    }
}
// if you try to execute query here, it will work.
class Controller extends Model
{
    public $f3, $db;

    public function __construct($f3)
    {
        $this->f3 = $f3;
        $this->connect();
    }   
}
class Model_Home extends Model
{
    public $f3, $db;

    public static function getUsers()
    {
        $query = "SELECT * FROM users";
        $result = $this->db->query($query);
        $output = '';
        while ($row = $result->fetch(PDO::FETCH_ASSOC)) {
            $output.= '<tr>
                            <td>'.$row['attrib1'].'</td>
                            <td>'.$row['attrib2'].'</td>
                            <td>'.$row['attrib3'].'</td>
                            <td>'.$row['attrib4'].'</td>
                            <td>'.$row['attrib5'].'</td>
                      </tr>';
        }

        return $output;
    }
}
class Controller_Home extends Controller
{
    public $f3, $db;

    public function main($output = '')
    {
        //setting up the variables
        $this->f3->set('getUsersTable', Model_Home::getUsers());
       // getUsersTable is a variable that will be passed to the view to reder

        //calling the view
        $this->f3->set('main','views/home/main.html');
    }
}
<h1>All Users</h1></br>
<?php echo htmlspecialchars_decode($getUsersTable); ?>
  • 资产
    • css
    • js
  • 控制器
    • Controller.php
    • Home_Controller.php
  • lib(包含框架内容)
  • 模型
    • Model.php
    • Model_Home.php
  • 观点
      • main.html
  • index.php
在index.php中,我调用框架(控制器和模型,包括数据库连接),并按如下方式创建路由:

// Kickstart the framework
$f3=require($_SERVER['DOCUMENT_ROOT'] . '/project_name/lib/base.php');
$f3->set('AUTOLOAD',''.$_SERVER['DOCUMENT_ROOT'] . '/project_name/controllers/; '.$_SERVER['DOCUMENT_ROOT'] . '/project_name/models/');

$f3->set('DEBUG',3);
if ((float)PCRE_VERSION<7.9){
    trigger_error('PCRE version is out of date');
}

if (!($f3->get('DEBUG')))
{
    $f3->set('ONERROR',
        function($f3) {
                $f3->reroute('/');
        }
    );
}

/****************** Start Routing the URLs ******************/

/****** Home Controller ******/
$f3->route('GET|HEAD /',
    function($f3) {
        $f3->reroute('/home');
    }
);

$f3->route('GET|HEAD /index',
    function($f3) {
        $f3->reroute('/home');
    }
);

$f3->route('GET /home','Controller_Home->main');

$f3->run();
class Model
{
    public $f3, $db;

    public function connect()
    {   
        global $db;

        $username = 'username';
        $password = 'password';
        $hostname = 'hostname';
        $dbname = 'dbname';

        try{
            $db = new PDO("mysql:host=$hostname;dbname=$dbname", $username, $password);
            $db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
        }
        catch(PDOException $e){
            echo $e->getMessage();
        }
        print_r($db); // this will give PDO Object ( )
        $this->db = $db;
    }
}
// if you try to execute query here, it will work.
class Controller extends Model
{
    public $f3, $db;

    public function __construct($f3)
    {
        $this->f3 = $f3;
        $this->connect();
    }   
}
class Model_Home extends Model
{
    public $f3, $db;

    public static function getUsers()
    {
        $query = "SELECT * FROM users";
        $result = $this->db->query($query);
        $output = '';
        while ($row = $result->fetch(PDO::FETCH_ASSOC)) {
            $output.= '<tr>
                            <td>'.$row['attrib1'].'</td>
                            <td>'.$row['attrib2'].'</td>
                            <td>'.$row['attrib3'].'</td>
                            <td>'.$row['attrib4'].'</td>
                            <td>'.$row['attrib5'].'</td>
                      </tr>';
        }

        return $output;
    }
}
class Controller_Home extends Controller
{
    public $f3, $db;

    public function main($output = '')
    {
        //setting up the variables
        $this->f3->set('getUsersTable', Model_Home::getUsers());
       // getUsersTable is a variable that will be passed to the view to reder

        //calling the view
        $this->f3->set('main','views/home/main.html');
    }
}
<h1>All Users</h1></br>
<?php echo htmlspecialchars_decode($getUsersTable); ?>
现在,在Controller.php中,我在结构内部调用Model.php中的connect()函数,如下所示:

// Kickstart the framework
$f3=require($_SERVER['DOCUMENT_ROOT'] . '/project_name/lib/base.php');
$f3->set('AUTOLOAD',''.$_SERVER['DOCUMENT_ROOT'] . '/project_name/controllers/; '.$_SERVER['DOCUMENT_ROOT'] . '/project_name/models/');

$f3->set('DEBUG',3);
if ((float)PCRE_VERSION<7.9){
    trigger_error('PCRE version is out of date');
}

if (!($f3->get('DEBUG')))
{
    $f3->set('ONERROR',
        function($f3) {
                $f3->reroute('/');
        }
    );
}

/****************** Start Routing the URLs ******************/

/****** Home Controller ******/
$f3->route('GET|HEAD /',
    function($f3) {
        $f3->reroute('/home');
    }
);

$f3->route('GET|HEAD /index',
    function($f3) {
        $f3->reroute('/home');
    }
);

$f3->route('GET /home','Controller_Home->main');

$f3->run();
class Model
{
    public $f3, $db;

    public function connect()
    {   
        global $db;

        $username = 'username';
        $password = 'password';
        $hostname = 'hostname';
        $dbname = 'dbname';

        try{
            $db = new PDO("mysql:host=$hostname;dbname=$dbname", $username, $password);
            $db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
        }
        catch(PDOException $e){
            echo $e->getMessage();
        }
        print_r($db); // this will give PDO Object ( )
        $this->db = $db;
    }
}
// if you try to execute query here, it will work.
class Controller extends Model
{
    public $f3, $db;

    public function __construct($f3)
    {
        $this->f3 = $f3;
        $this->connect();
    }   
}
class Model_Home extends Model
{
    public $f3, $db;

    public static function getUsers()
    {
        $query = "SELECT * FROM users";
        $result = $this->db->query($query);
        $output = '';
        while ($row = $result->fetch(PDO::FETCH_ASSOC)) {
            $output.= '<tr>
                            <td>'.$row['attrib1'].'</td>
                            <td>'.$row['attrib2'].'</td>
                            <td>'.$row['attrib3'].'</td>
                            <td>'.$row['attrib4'].'</td>
                            <td>'.$row['attrib5'].'</td>
                      </tr>';
        }

        return $output;
    }
}
class Controller_Home extends Controller
{
    public $f3, $db;

    public function main($output = '')
    {
        //setting up the variables
        $this->f3->set('getUsersTable', Model_Home::getUsers());
       // getUsersTable is a variable that will be passed to the view to reder

        //calling the view
        $this->f3->set('main','views/home/main.html');
    }
}
<h1>All Users</h1></br>
<?php echo htmlspecialchars_decode($getUsersTable); ?>
Model_Home.php具有如下查询数据库的函数:

// Kickstart the framework
$f3=require($_SERVER['DOCUMENT_ROOT'] . '/project_name/lib/base.php');
$f3->set('AUTOLOAD',''.$_SERVER['DOCUMENT_ROOT'] . '/project_name/controllers/; '.$_SERVER['DOCUMENT_ROOT'] . '/project_name/models/');

$f3->set('DEBUG',3);
if ((float)PCRE_VERSION<7.9){
    trigger_error('PCRE version is out of date');
}

if (!($f3->get('DEBUG')))
{
    $f3->set('ONERROR',
        function($f3) {
                $f3->reroute('/');
        }
    );
}

/****************** Start Routing the URLs ******************/

/****** Home Controller ******/
$f3->route('GET|HEAD /',
    function($f3) {
        $f3->reroute('/home');
    }
);

$f3->route('GET|HEAD /index',
    function($f3) {
        $f3->reroute('/home');
    }
);

$f3->route('GET /home','Controller_Home->main');

$f3->run();
class Model
{
    public $f3, $db;

    public function connect()
    {   
        global $db;

        $username = 'username';
        $password = 'password';
        $hostname = 'hostname';
        $dbname = 'dbname';

        try{
            $db = new PDO("mysql:host=$hostname;dbname=$dbname", $username, $password);
            $db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
        }
        catch(PDOException $e){
            echo $e->getMessage();
        }
        print_r($db); // this will give PDO Object ( )
        $this->db = $db;
    }
}
// if you try to execute query here, it will work.
class Controller extends Model
{
    public $f3, $db;

    public function __construct($f3)
    {
        $this->f3 = $f3;
        $this->connect();
    }   
}
class Model_Home extends Model
{
    public $f3, $db;

    public static function getUsers()
    {
        $query = "SELECT * FROM users";
        $result = $this->db->query($query);
        $output = '';
        while ($row = $result->fetch(PDO::FETCH_ASSOC)) {
            $output.= '<tr>
                            <td>'.$row['attrib1'].'</td>
                            <td>'.$row['attrib2'].'</td>
                            <td>'.$row['attrib3'].'</td>
                            <td>'.$row['attrib4'].'</td>
                            <td>'.$row['attrib5'].'</td>
                      </tr>';
        }

        return $output;
    }
}
class Controller_Home extends Controller
{
    public $f3, $db;

    public function main($output = '')
    {
        //setting up the variables
        $this->f3->set('getUsersTable', Model_Home::getUsers());
       // getUsersTable is a variable that will be passed to the view to reder

        //calling the view
        $this->f3->set('main','views/home/main.html');
    }
}
<h1>All Users</h1></br>
<?php echo htmlspecialchars_decode($getUsersTable); ?>
最后是main.html页面,如下所示:

// Kickstart the framework
$f3=require($_SERVER['DOCUMENT_ROOT'] . '/project_name/lib/base.php');
$f3->set('AUTOLOAD',''.$_SERVER['DOCUMENT_ROOT'] . '/project_name/controllers/; '.$_SERVER['DOCUMENT_ROOT'] . '/project_name/models/');

$f3->set('DEBUG',3);
if ((float)PCRE_VERSION<7.9){
    trigger_error('PCRE version is out of date');
}

if (!($f3->get('DEBUG')))
{
    $f3->set('ONERROR',
        function($f3) {
                $f3->reroute('/');
        }
    );
}

/****************** Start Routing the URLs ******************/

/****** Home Controller ******/
$f3->route('GET|HEAD /',
    function($f3) {
        $f3->reroute('/home');
    }
);

$f3->route('GET|HEAD /index',
    function($f3) {
        $f3->reroute('/home');
    }
);

$f3->route('GET /home','Controller_Home->main');

$f3->run();
class Model
{
    public $f3, $db;

    public function connect()
    {   
        global $db;

        $username = 'username';
        $password = 'password';
        $hostname = 'hostname';
        $dbname = 'dbname';

        try{
            $db = new PDO("mysql:host=$hostname;dbname=$dbname", $username, $password);
            $db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
        }
        catch(PDOException $e){
            echo $e->getMessage();
        }
        print_r($db); // this will give PDO Object ( )
        $this->db = $db;
    }
}
// if you try to execute query here, it will work.
class Controller extends Model
{
    public $f3, $db;

    public function __construct($f3)
    {
        $this->f3 = $f3;
        $this->connect();
    }   
}
class Model_Home extends Model
{
    public $f3, $db;

    public static function getUsers()
    {
        $query = "SELECT * FROM users";
        $result = $this->db->query($query);
        $output = '';
        while ($row = $result->fetch(PDO::FETCH_ASSOC)) {
            $output.= '<tr>
                            <td>'.$row['attrib1'].'</td>
                            <td>'.$row['attrib2'].'</td>
                            <td>'.$row['attrib3'].'</td>
                            <td>'.$row['attrib4'].'</td>
                            <td>'.$row['attrib5'].'</td>
                      </tr>';
        }

        return $output;
    }
}
class Controller_Home extends Controller
{
    public $f3, $db;

    public function main($output = '')
    {
        //setting up the variables
        $this->f3->set('getUsersTable', Model_Home::getUsers());
       // getUsersTable is a variable that will be passed to the view to reder

        //calling the view
        $this->f3->set('main','views/home/main.html');
    }
}
<h1>All Users</h1></br>
<?php echo htmlspecialchars_decode($getUsersTable); ?>
我必须使用的php版本是5.4(相当旧)。任何想法,请


谢谢大家

您已经将Model_Home::getUsers定义为静态方法。这意味着它是类的一个方法,而不是实例化对象,这反过来意味着您不能访问对象属性,只能访问定义为“静态”的类属性和方法$db没有定义为“静态”,因此它是对象的属性,而不是类的属性

如果要将getUsers保持为静态:

您可以将$db定义为“static”(对于引用它的任何代码,都需要对其他代码进行更改),也可以使用Singleton模式,将对象的实例存储为静态类变量,以供其他类方法访问。例如:

class myClass
{
    protected static $db = null;

    public static function getDb()
    {
        if(empty(self::$db))
            self::$db = new Database();

        return self::$db;
    }
}
如果您不想让getUsers保持静态:

只需从声明中删除“static”关键字,您还必须从以下位置更新此方法调用:

$this->f3->set('getUsersTable', Model_Home::getUsers());
致:


您已经将Model_Home::getUsers定义为静态方法。这意味着它是类的一个方法,而不是实例化对象,这反过来意味着您不能访问对象属性,只能访问定义为“静态”的类属性和方法$db没有定义为“静态”,因此它是对象的属性,而不是类的属性

如果要将getUsers保持为静态:

您可以将$db定义为“static”(对于引用它的任何代码,都需要对其他代码进行更改),也可以使用Singleton模式,将对象的实例存储为静态类变量,以供其他类方法访问。例如:

class myClass
{
    protected static $db = null;

    public static function getDb()
    {
        if(empty(self::$db))
            self::$db = new Database();

        return self::$db;
    }
}
如果您不想让getUsers保持静态:

只需从声明中删除“static”关键字,您还必须从以下位置更新此方法调用:

$this->f3->set('getUsersTable', Model_Home::getUsers());
致:


首先,在尝试创建这种骨架之前,先熟悉f3。您发布的代码似乎表明,您可以充分利用一些您可能不熟悉的关键概念

使用模板使用
echo\template::instance()->render('templates/controller_index.htm')从控制器调用模板

使用F3 ORM尽管与其他一些ORM(如Eloquent)相比有一定的局限性,但F3 ORM确实加快了处理数据库的速度。请在此阅读:

基于您拥有的模型代码,我想说,您完全可以不使用任何模型,使用Mapper类可以让您走很长的路

将配置存储在配置文件中。这将从逻辑中分离配置信息。

这里定义的任何值都可以像全局变量一样访问

[globals]
DEBUG=0
CACHE=true

; Database
db.host=localhost
db.port=3306
db.user=root
db.pass=
db.name=phproject

; Session lifetime
; Also set session.gc_maxlifetime in php.ini
JAR.expire=604800

就像这样

// Connect to database
$f3->set("db.instance", new DB\SQL(
    "mysql:host=" . $f3->get("db.host") . ";port=" . $f3->get("db.port") . ";dbname=" . $f3->get("db.name"),
    $f3->get("db.user"),
    $f3->get("db.pass")
));
如果在调用任何控制器之前将该代码放入索引文件中,则可以轻松调用数据库连接。使用
$f3->set(“db.instance”,…)
创建并设置连接

// get reference to instance and initialize mapper
$user = new DB\SQL\Mapper($f3->get("db.instance"),'users');

// get all records (same as SELECT * FROM $tablename) and put them inside all_users var
$f3->set('all_users', $user->find());
如果您在模板文件中使用这些信息,您可以这样做

<table>
<repeat group="{{ @all_users }}" value="{{ @user }}">
    <tr>
        <td>{{ @user.attrib1 }}</td>
        <td>{{ @user.attrib2 }}</td>
        <td>{{ @user.attrib3 }}</td>
    </tr>
</repeat>
</table>

{{@user.attrib1}
{{@user.attrib2}
{{@user.attrib3}

首先,在尝试创建这种骨架之前,先熟悉f3。您发布的代码似乎表明,您可以充分利用一些您可能不熟悉的关键概念

使用模板使用
echo\template::instance()->render('templates/controller_index.htm')从控制器调用模板

使用F3 ORM尽管与其他一些ORM(如Eloquent)相比有一定的局限性,但F3 ORM确实加快了处理数据库的速度。请在此阅读:

基于您拥有的模型代码,我想说,您完全可以不使用任何模型,使用Mapper类可以让您走很长的路

将配置存储在配置文件中。这将从逻辑中分离配置信息。

这里定义的任何值都可以像全局变量一样访问

[globals]
DEBUG=0
CACHE=true

; Database
db.host=localhost
db.port=3306
db.user=root
db.pass=
db.name=phproject

; Session lifetime
; Also set session.gc_maxlifetime in php.ini
JAR.expire=604800

就像这样

// Connect to database
$f3->set("db.instance", new DB\SQL(
    "mysql:host=" . $f3->get("db.host") . ";port=" . $f3->get("db.port") . ";dbname=" . $f3->get("db.name"),
    $f3->get("db.user"),
    $f3->get("db.pass")
));
如果在调用任何控制器之前将该代码放入索引文件中,则可以轻松调用数据库连接。使用
$f3->set(“db.instance”,…)
创建并设置连接

// get reference to instance and initialize mapper
$user = new DB\SQL\Mapper($f3->get("db.instance"),'users');

// get all records (same as SELECT * FROM $tablename) and put them inside all_users var
$f3->set('all_users', $user->find());
如果您在模板文件中使用这些信息,您可以这样做

<table>
<repeat group="{{ @all_users }}" value="{{ @user }}">
    <tr>
        <td>{{ @user.attrib1 }}</td>
        <td>{{ @user.attrib2 }}</td>
        <td>{{ @user.attrib3 }}</td>
    </tr>
</repeat>
</table>

{{@user.attrib1}
{{@user.attrib2}
{{@user.attrib3}

Ok,那么您要说的是创建一个静态调用DB的函数,并将该函数放入模型中。phpOr我刚才添加的第二个选项是从函数声明中删除“static”吗?很抱歉,上载到服务器不起作用,因此它没有更改错误消息。。现在错误消息是致命错误:调用成员函数