在自制MVC框架中实现PHP Activerecord
我正在尝试为我自己的小型PHP MVC框架实现一个PHPActiveRecord。但它只适用于几个表,而不适用于其他表。 好的,我的MVC结构如下:在自制MVC框架中实现PHP Activerecord,php,phpactiverecord,Php,Phpactiverecord,我正在尝试为我自己的小型PHP MVC框架实现一个PHPActiveRecord。但它只适用于几个表,而不适用于其他表。 好的,我的MVC结构如下: index.php - assets - config/ - core/ - Bootstrap.php - Controller.php - Model.php - View.php - etc - libs/ - php-activerecord/ - ActiveRecord.php -
index.php
- assets
- config/
- core/
- Bootstrap.php
- Controller.php
- Model.php
- View.php
- etc
- libs/
- php-activerecord/
- ActiveRecord.php
- others
- app/
- activerecords/
- controllers/
- models/
- views/
我是如何实现Activerecord的:
index.php
- assets
- config/
- core/
- Bootstrap.php
- Controller.php
- Model.php
- View.php
- etc
- libs/
- php-activerecord/
- ActiveRecord.php
- others
- app/
- activerecords/
- controllers/
- models/
- views/
Model.php
class Model
{
function __construct()
{
require_once 'libs/php-activerecord/ActiveRecord.php';
ActiveRecord\Config::initialize(function($cfg)
{
$cfg->set_model_directory('app/activerecords');
$cfg->set_connections(array(
'development' => 'mysql://root:@localhost/db_name'));
});
}
}
例如,我有两个表,城市和实验室。
问题是,当从城市检索数据时,它工作得很好,但当从实验室检索数据时,它出现了一个错误:“调用未定义的方法Laboratory::find”
代码如下:
餐桌城市
位置:activerecords/City.php
class City extends ActiveRecord\Model
{
}
桌面实验室
位置:activerecords/Laboratory.php
class Laboratory extends ActiveRecord\Model
{
}
索引控制器
位置:controllers/indexController.php
class Index extends Controller
{
function __construct()
{
parent::__construct();
Session::init();
}
function index()
{
$this->view->cityLists = $this->model->getCityLists();
$this->view->laboratoryLists = $this->model->getLaboratoryLists();
$this->view->render('home/index');
}
}
模型
位置:models/indexModel.php
class indexModel extends Model
{
function __construct()
{
parent::__construct();
}
function getLaboratoryLists()
{
return Laboratory::find('all');
}
function getCityLists()
{
return City::find('all');
}
}
观点
位置:views/home/index.php
foreach($this->cityLists as $key){
echo $key->id.' - '.$key->name;
}
foreach($this->laboratoryLists as $key){
echo $key->id.' - '.$key->name;
}
在浏览器中,可以加载城市列表,但可以加载来自表格实验室的数据。浏览器显示:“调用未定义的方法实验室::查找” 有人能告诉我我的密码有什么问题吗?这是因为PHPActiveRecord的惯例还是其他
谢谢你之前。。。对不起,我的英语很差。很抱歉通知您,MVC中的“模型”不是类或对象。模型是一个由许多类组成的层。虽然这可能是真的,但是
phpactiverecord
库确实有一个名为Model
的类,这就是问题所在。大量的“模型”类都扩展了这个类。也许这是一个不错的话题,但与问题主题无关:您的名称空间是如何定义的?可能是那里发生了什么有趣的事吗?