CakePHP模型:为什么使用实例方法?
为什么所有的CakePHP模型方法都是实例方法。例如:CakePHP模型:为什么使用实例方法?,php,oop,cakephp,orm,cakephp-model,Php,Oop,Cakephp,Orm,Cakephp Model,为什么所有的CakePHP模型方法都是实例方法。例如: $post = $this->Post->findById($id); $post = ...; $post->publish(); // Would be $this->Post->publish($id) using Cake $post = Post::findById($id); // Would be $this->Post->findById($id) using Cake $ne
$post = $this->Post->findById($id);
$post = ...;
$post->publish(); // Would be $this->Post->publish($id) using Cake
$post = Post::findById($id); // Would be $this->Post->findById($id) using Cake
$newPost = Post::create(['title' => 'My post', 'body' => '<p>...</p>']);
// Would be $newPost = $this->Post->create([...]); using Cake
代替
$post = Post::find($id);
我认为所有在模型实例(或记录)上工作的方法都是实例方法,例如:
$post = $this->Post->findById($id);
$post = ...;
$post->publish(); // Would be $this->Post->publish($id) using Cake
$post = Post::findById($id); // Would be $this->Post->findById($id) using Cake
$newPost = Post::create(['title' => 'My post', 'body' => '<p>...</p>']);
// Would be $newPost = $this->Post->create([...]); using Cake
所有创建或查找记录的方法(处理记录的总集合)都是类方法(实例方法),例如:
$post = $this->Post->findById($id);
$post = ...;
$post->publish(); // Would be $this->Post->publish($id) using Cake
$post = Post::findById($id); // Would be $this->Post->findById($id) using Cake
$newPost = Post::create(['title' => 'My post', 'body' => '<p>...</p>']);
// Would be $newPost = $this->Post->create([...]); using Cake
$post=post::findById($id);//将是$this->Post->findById($id)使用Cake
$newPost=Post::create(['title'=>“我的帖子”,“body'=>”..');
//将是$newPost=$this->Post->create([…]);用蛋糕
我认为这个蛋糕约定与逻辑OOP约定相反。有人知道这种设计的原因吗?- 静态调用或单例使依赖项注入难以使用,也使代码难以测试。您正在创建紧密耦合的代码-不好。你想要的
- 当通过关联使用模型时,将创建一个新实例,这就是为什么存在模型的alias属性。您可以将完全不同的行为绑定到它,或者以其他方式更改它的状态
- 您希望能够修改和重载属性和方法,并动态创建新实例。示例:具有同一表的两个模型实例,但写入两个数据库。对于使用DB连接的应用程序来说,这是一个非常常见的场景,具体取决于登录用户或vhost(例如)
- 很明显,您不想仅仅为了扩展模型而经历这些:
若您想要那个种“外观”或认为您“需要”它,您可以使用Laravel而不是CakePHP,因为CakePHP在几乎所有方面都过度使用。但我向您保证,这不会使您的代码变得更好。这几乎可以肯定,因为每个模型都需要具有单独设置的功能,因此模型最好能够具有存储这些设置的状态。例如,模型关系和验证规则是常用的设置,在各个模型之间高度可变。但是静态变量呢?例如:类Post扩展了模型{static$validations=array(…);static$belongsTo='User';}静态属性不能被继承覆盖,当然CakePHP中所有用户定义的模型都是从模型继承的,所以这不会真正起作用。如果使用Static::$variable而不是self::$variable引用静态属性,则静态属性可以被继承覆盖,对吗?