use cakephp component inside a model

点点圈 提交于 2019-12-21 07:26:39

问题


How do I use a component that I created in cakePHP inside one of my model classes? Is this possible?

If so, please let me know how I can do so


回答1:


It is possible but pretty bad practice in a MVC framework. You should re-think and re-organize your code if you think you need to use the component in a model because something is cleary wrong then.

A component is thought to share code between controllers, only between controllers.

  • Components in CakePHP 1.3
  • Components in CakePHP 2.x
  • Components in CakePHP 3.x

To share re-usable code between models it would be a behavior. For a view it would be a helper.

If you have some really generic code it should be a lib or put it in the Utility folder / namespace or create a new namespace. Check the existing classes there to get an idea what to put in there.

No code was provided so it is not possible to give any real recommendation on how to refactor it. However the way you want to use the existing code won't work in the MVC context, so time to rethink your approach of whatever you try to do.




回答2:


It is possible to use a component inside a model (but I cannot comment if this is a recommended or a best-practice).

Inspired from original source, an example to use a component called ‘Geocoder’ in a model:

App::import('Component','GeoCoder');
$gc = new GeoCoderComponent(new ComponentCollection);

Then you can use $gc to call the functions of the component.

--

P.S.: I do not want to encourage bad programming practices, but sometimes the pressure of deadlines (in real world projects) may force a developer to make such decisions.




回答3:


@AD7six

// Use anywhere
AuthComponent::user('id')

// From inside a controller
$this->Auth->user('id');

From the cake PHP documentation they provide AuthComponent::user('id') so that it can be used in places other than a controller.

Maybe I need a bigger hint, but why shouldn't my model be able to access ACL information ?



来源:https://stackoverflow.com/questions/9778254/use-cakephp-component-inside-a-model

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!