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

问题描述:

我正在使用第三方库以特定方式格式化数据。 我设法创建该库做以下组件:如何在CakePHP中使用外部库作为视图助手?

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 S中的供应商库,其中包括在需要的地方在我的控制器,因此我提供访问帮手在我看来的图书馆。

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

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

+0

当谈到加载供应商库,应用::导入实际上仅仅是'include'的一个包装。所以你应该可以在控制器中使用'App :: import',并且能够在相应的视图中访问该类。或者,写一个裸骨帮助器,它只是一个访问你的库的包装器,并将你的'App :: import'移动到那里。 – Kai 2014-10-17 23:02:05

+0

感谢您的评论@Kai。我遵循你的建议,并创建了一个骨干帮手。它工作的很好,但我正在寻找帮助我的帮助者有一个'csfStartup(null)'实例,当我调用它时,而不是创建一个新实例'$ this-> CSF = new csfStartup null)'在每个视图中。 关于如何构建帮手的任何建议? – kshaaban 2014-10-17 23:22:12

我最终创建了帮助程序,按照我的意愿工作,并发布了答案,以备别人希望在CakePHP中使用第三方类/库作为帮助程序。

savant#cakephp IRC频道设置我在正确的道路上创造了帮手,并与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; 
    } 
}