简体   繁体   English

Cake PHP中的控制器继承?

[英]Controller inheritance in Cake PHP?

Has anyone attempted this? 有人试过吗? Is it possible, and if so, what kind of problems will I run into if I try to accomplish it? 是否可能,如果是这样,如果我试图完成它会遇到什么样的问题?

If you goal is to share logic between controllers: 如果您的目标是在控制器之间共享逻辑:

  • add the logic to the AppController to share it with all the controllers in your app. 将逻辑添加到AppController以与应用程序中的所有控制器共享。

  • make a component and add that to $this->components for the controllers you want to share it. 制作一个组件并将其添加到要分享它的控制器的$ this-> components。

Adding additional inheritance between controllers should only be concidered as a last resort, as you have to pay extra attention to how components and helpers are handled. 在控制器之间添加额外的继承只应作为最后的手段,因为您必须特别注意如何处理组件和帮助程序。 Eg you must manually merge $this->components & $this->helpers with the AppController and the controller you are inheriting from. 例如,您必须手动将$ this-> components&$ this-> helpers与AppController和您继承的控制器合并。

I have put an additional layer between the AppController and some special controllers in an app. 我在AppController和应用程序中的一些特殊控制器之间添加了一个额外的层。

The only problem you'll run into is the merging of the $helpers and $components class attributes. 您将遇到的唯一问题是$ helpers和$ components类属性的合并。 In CakePHP, overriding those variables in your controllers will not overwrite those set by the AppController, but it will merge them. 在CakePHP中,覆盖控制器中的那些变量不会覆盖AppController设置的变量,但会合并它们。

This is done by a special method named __mergeVars() in the Controller base class, and it unfortunately does it only for the default controller structure. 这是通过Controller基类中名为__mergeVars()的特殊方法完成的,遗憾的是它仅针对默认控制器结构。 Your additional layer will not be merged correctly, if you want $helpers and $controllers inheritance from AppController down to your controllers. 如果您希望从AppController向控制器发送$ helper和$ controllers继承,则无法正确合并您的附加层。

You will run into issue with $components and $helpers properties not merging and instead overwriting. 您将遇到$components$helpers属性的问题,而不是合并而是覆盖。 Be sure to define protected $_mergeParent = 'YourParentClass' to have this done properly. 一定要定义protected $_mergeParent = 'YourParentClass'才能正确完成。 The default value for this is 'AppController' . 这个的默认值是'AppController'

Source code: http://api.cakephp.org/2.4/source-class-Controller.html#294-301 源代码: http//api.cakephp.org/2.4/source-class-Controller.html#294-301

Why not try? 为什么不试试? At least, it's already being done with the Controller -> AppController -> MyController classes. 至少,它已经完成了Controller - > AppController - > MyController类。

当然,你可以轻松地在Cake中继承控制器......然后你通常会利用他们的钩子函数,比如'beforeFilter','afterFilter'等来为你的控制器添加运行时逻辑。我通常至少放置一个抽象控制器在蛋糕控制器和您在路线中配置的最终控制器之间。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM