donglugou6652
donglugou6652
2013-07-31 10:06

cakephp使用组件作为控制器方法

已采纳

I'm trying to find the best, cleanest way of initialising a method from within another controller. I basically want to record 'likes', 'posts' etc as 'actions' when they happen.

Actions are working fine on submission, but not from outside it's own controller.

In the LikesController, I want to be able to simply go:

$this->Action->add($fields);

But this doesn't work, even if I do $this->loadModel('Action'); beforehand. After reading around it seems that 'components' is the way to go...

So I was wondering how I would achieve this using components. I've got this so far in my LikesController:

public $components = array(
    'RequestHandler','Helper',
        'Action' => array('controller'=>'actions', 'action'=>'add'),
);

But still no joy when I try to call $this->Action->add.

What is the best method of doing this, and how can I set up the component class to work as though it is the Action controller, and able to use its methods?

If I can award REP to the best answer then I will..! Many thanks in advance.

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 复制链接分享
  • 邀请回答

1条回答

  • du9826 du9826 8年前

    A component isn't the same as a model. So if you want to do things this way, you'll have to turn your Action model into a Component.

    The component would go into Controller/Component/ActionComponent.php, and then it can be included into your Controllers like this:

    public $components = array(..., 'Action');
    

    The logic in your Component can be similar to that in a Model, but there are some differences. For example, you could still have an Action model, and the component can use that for CRUD and other stuff. You'll have to use ClassRegistry::init() to load a model into your Component though.

    I can't really explain how to do exactly what you want, one reason for that being that I don't know precisely enough what it is you do want. However, I've written my own Component before and you can use it for reference if you like - it's possibly more complicated than yours so you can see how to write methods for it.

    Custom ACL Component

    In that example, once it's included in a Controller, I can simply call $this->CustomAcl->check() anywhere I like.

    I hope this is enough to get you started at least.

    点赞 评论 复制链接分享

相关推荐