小编Luk*_*cki的帖子

避免代码重复 - 最好的方法

我有两个方法具有相同的列表和类型的参数和几乎相同的主体,但每个方法调用另一个函数来获取元素列表.更确切地说:



    public void method1 (int a, int b) {
            //body (the same in both of methods)
            List<SomeObject> list = service.getListA(int c, int d);
            //rest of the body (the same in both of methods)
        }

        public void method2 (int a, int b) {
            //body (the same in both of methods)
            List<SomeObject> list = service.getListB(int c, int d, int e);
            //rest of the body (the same in both of methods)
        }

Run Code Online (Sandbox Code Playgroud)

在这种情况下,避免代码重复的问题的最佳方法是什么?我想到了战略模式,但是参数列表存在差异.

更新:



    public void method1 (int a, int b) {
            //body …
Run Code Online (Sandbox Code Playgroud)

java design-patterns

5
推荐指数
1
解决办法
221
查看次数

在自定义组件中使用会话组件

我正在尝试在自定义组件(CakePHP 2.3)中使用Session组件,但是当我调用Session组件函数时,我得到:致命错误:在...\app\Controller \中的非对象上调用成员函数read()第7行的Component\CartComponent.php

我的CartComponent看起来像这样:

<?php
App::uses('Component', 'Controller');
class CartComponent extends Component {
    public $components = array('Session');

    function hasItems() {
        $cart = $this->Session->read('Cart');
        return $cart != null && count($cart) > 0;
    }

}
?>
Run Code Online (Sandbox Code Playgroud)

我在控制器中使用它:

<?php
class OrdersController extends AppController {
    public $name = 'Orders';
    public $components = array('Cart', 'Email');

    function beforeFilter() {
        parent::beforeFilter();
        if ($this->Cart->hasItems()) {
            $this->Auth->allow('add_item', 'remove_item', 'cart');
        } else {
            $this->Auth->allow('add_item', 'remove_item', 'cart', 'make');
        }
    }
}
?>
Run Code Online (Sandbox Code Playgroud)

cakephp cakephp-2.0 cakephp-2.3

2
推荐指数
1
解决办法
5555
查看次数