如何在CakePHP中使用外部库作为视图助手?

时间:2014-10-17 22:49:59

标签: cakephp cakephp-2.5

我使用第三方库以特定方式格式化数据。 我设法从该库创建一个组件,执行以下操作:

App::uses('Component', 'Controller');
App::import('Vendor','csformat' ,array('file'=>'csformat'.DS.'csformat.php'));

class CSFormatComponent extends Component {

    public function startup(Controller $controller){
        $controller->CSF = new csfStartup(null);
        return $controller->CSF;
    }
}

这样做可以让我通过我的控制器访问库提供的不同类。但是我意识到我会做很多不必要的$this->set($one, $two)来将格式化的数据从控制器传递到视图,其中基本上库可以作为帮助器更有用,因为我可以在视图上格式化我的数据

任何想法如何创建这样的帮助?

更新

根据下面评论中的Kai建议,我创建了一个简单的帮助器,App::import是供应商库,并包含了我的控制器所需的帮助器,因此为我提供了帮助在我的观点中访问图书馆。

我现在的问题是,我不想在每个视图中不断地实例化图书馆的csfStartup课程。

有没有办法让我的助手在调用助手时随时提供该类的实例?与我的组件工作方式类似。

1 个答案:

答案 0 :(得分:0)

我最终创建了帮助程序,以便按照我的意愿工作,并且我发布了答案,以防其他人希望将第三方类/库用作CakePHP中的帮助程序。

savant IRC频道上的

#cakephp让我走上正确的道路来创建帮助,并且通过对Helper.php API的一些研究,我最终得到了:

App::uses('AppHelper', 'View/Helper');
App::import('Vendor','csformat' ,array('file'=>'csformat'.DS.'csformat.php')); 

class CSFHelper extends AppHelper{

    protected $_CSF = null;

    // Attach an instance of the class as an attribute
    public function __construct(View $View, $settings = array()){
        parent::__construct($View, $settings);
        $this->_CSF= new csfStartup(null);
    }

    // PHP magic methods to access the protected property
    public function __get($name) {
        return $this->_CSF->{$name};
    }

    public function __set($name, $value) {
        $this->_CSF->{$name} = $value;
    }

    // Route calls made from the Views to the underlying vendor library
    public function __call($name, $arguments) {
        $theCall = call_user_func_array(array($this->_CSF, $name), $arguments);
        return $theCall;
    }
}