如何将 cakephp 2.x 组件和助手转换为 1.3


How to convert cakephp 2.x component and helper to 1.3

我有一个裁剪工具组件和助手,可以在 cakephp 2.x 上运行,但现在我需要将此裁剪工具用于 cakephp 1.3 中的一个旧项目。我应该怎么做?

该组件:

<?php
    App::uses('Component', 'Controller');
    class JcropComponent extends Component {
        public $components = array('Session');
        public $options = array(
            'overwriteFile' => true,
            'boxWidth' => '940'
        );
        /**
         * Constructor
         */
        public function __construct(ComponentCollection $collection, $options = array()) {
            parent::__construct($collection,$options);
            $this->options = array_merge($this->options, $options);
        }
?>

帮手

<?php
App::uses('AppHelper', 'View/Helper');
class JcropHelper extends AppHelper {
    public $helpers = array('Html','Form','Js');
    public $options = array(
        'tooltip' => true,
        'boxWidth' => '940'
    );

    public function __construct(View $view, $options = null) {
        parent::__construct($view,$options);
        $this->options = array_merge($this->options, $options);
    }
?>

我试图将其更改为此,它可以显示图像,但是如何合并选项数组?其中__construct($options = array())

<?php
    class JcropComponent extends Component {
        var $components = array('Session');
        public $options = array(
            'overwriteFile' => true,
            'boxWidth' => '940'
        );
    //public function initialize(&$controller, $settings = array()) {
    //  $this->controller =& $controller;
        //parent::__construct($collection,$options);
        //$this->options = array_merge($this->options, $options);
    //}
?>

<?php
class JcropHelper extends AppHelper {
    var $helpers = array('Html','Form','Js');
    public $options = array(
        'tooltip' => true,
        'boxWidth' => '940'
    );

    public function __construct($settings = null) {
        //parent::__construct($view,$options);
        //$this->options = array_merge($this->options, $options);
    }
?>

1.3 中的组件不使用构造函数进行设置

您遇到的第一个重要问题是:组件接收在主要版本之间更改的设置的方式。

在 1.3 中:

//Component(Collection) Class
$component->initialize($controller, $settings);

在 2.x 中:

//ComponentCollection class
new $componentClass(ComponentCollectionObject, $settings);

因此,使组件在 1.3 中以相同的方式工作的方法是定义初始化方法。

帮助程序具有不同的构造函数

对帮助程序进行了类似的更改:

在 1.3 中:

//View class
new $helperCn($options);

在 2.x 中:

//HelperCollection class
new $helperClass(ViewObject, $settings);

在这种情况下,它应该更明显 - 任何被重写的方法都应该具有与父类相同的方法签名。因此:更改帮助程序以在构造函数中具有相同的预期参数

警告:扩展组件

在 1.3 中,组件扩展组件,而是扩展对象。组件是充当 1.3 中集合的类,扩展它会导致意外和不希望的行为(即它可能会导致意外的"随机"警告和致命错误)。因此,您应该将组件类更改为类似于所有其他组件,扩展 Object(或者很简单 - 不扩展组件)。

如果这个类是你在各种项目中使用和维护的东西,那么最好将主要功能提取到一个独立的类中,并只实现一个精简包装类(组件/行为)来与之交互。通过这种方式,无论使用什么版本的 cake 或任何其他框架,都可以利用对主要功能所做的任何更改。