dpquu9206 2014-09-15 20:27 采纳率: 0%
浏览 39

CakePHP模型:为什么实例方法?

Why exactly are all CakePHP Model methods instance methods. For example:

$post = $this->Post->findById($id);

in stead of

$post = Post::find($id);

I would think all methods that work on model instances (or records) would be instance methods, for example:

$post = ...;
$post->publish(); // Would be $this->Post->publish($id) using Cake

and all methods that create or find records (that work on the total collection of records) would be class methods (instance methods), for example:

$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

I think this Cake convention is contrary to logical OOP conventions. Does anyone know the reason of this design?

  • 写回答

1条回答 默认 最新

  • doulin1867 2014-09-16 01:38
    关注
    • Static calls or singletons make it hard to use dependency injection and make it hard to test your code. You're creating tight coupled code - not good. You want loose coupling.
    • When models are used through associations a new instance is created, that's why there is the alias property of the model. You can bind totally different behaviours to it or change it's state in other ways.
    • You want to be able to modify and overload properties and methods and creating new instances on the fly. Example: Have two model instances of the same table but write into two DBs. This is a very like to happen scenario for apps that use DB connections depending on the logged in user or vhost for example.
    • You clearly don't want to go through this just to extend a model: Extending singletons in PHP

    I think this Cake convention is contrary to logical OOP conventions. Does anyone know the reason of this design?

    What you describe is not logical nor good practice. Well, you could provide some links that would explain why you consider this as "logical OOP conventions". There are no conventions but design patterns. A good use case are "utility" classes like the classes inside the "Utility" folder of CakePHP. There is no need to have multiple instances of them.

    See these questions and links as well:

    If you want that "look" or think you "need" it, you can use Laravel instead of CakePHP which makes excessive use of the facade pattern for almost everything. But I guarantee you this won't make your code better.

    评论

报告相同问题?

悬赏问题

  • ¥15 如何用Labview在myRIO上做LCD显示?(语言-开发语言)
  • ¥15 Vue3地图和异步函数使用
  • ¥15 C++ yoloV5改写遇到的问题
  • ¥20 win11修改中文用户名路径
  • ¥15 win2012磁盘空间不足,c盘正常,d盘无法写入
  • ¥15 用土力学知识进行土坡稳定性分析与挡土墙设计
  • ¥70 PlayWright在Java上连接CDP关联本地Chrome启动失败,貌似是Windows端口转发问题
  • ¥15 帮我写一个c++工程
  • ¥30 Eclipse官网打不开,官网首页进不去,显示无法访问此页面,求解决方法
  • ¥15 关于smbclient 库的使用