2014-10-17 60 views
0

我正在使用第三方庫以特定方式格式化數據。 我設法創建該庫做以下組件:如何在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

回答

0

我最終創建了幫助程序,按照我的意願工作,併發布了答案,以備別人希望在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; 
    } 
}