0

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

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)来将格式化的数据从控制器传递到视图,从本质上讲,库作为助手可能会更有益,因为我可以在视图上格式化我的数据。

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

更新:

根据下面评论的PerKai的建议,我创建了一个基本的帮助程序,它App::import是供应商库,并在我的控制器中需要的地方包含了帮助程序,因此我可以在我的视图中访问该库。

我现在的问题是我不想csfStartup在每个视图中都不断地实例化库的类。

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

4

1 回答 1

0

我最终创建了助手以按我的意愿工作,并且我发布了答案,以防其他人希望在 CakePHP 中使用第三方类/库作为助手。

savant#cakephpIRC 频道上,我走上了创建助手的正确道路,并且通过对Helper.phpAPI 的一些研究,我最终得到了:

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;
    }
}
于 2014-10-19T05:54:45.547 回答