use cakephp component inside a model

后端 未结 3 2095
长发绾君心
长发绾君心 2021-02-13 05:03

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

相关标签:
3条回答
  • 2021-02-13 05:37

    @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 ?

    0 讨论(0)
  • 2021-02-13 05:47

    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.

    0 讨论(0)
  • 2021-02-13 05:47

    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.

    0 讨论(0)
提交回复
热议问题