dongleman4760 2015-06-27 05:33
浏览 39

如何在cakephp中的控制器之间传递变量?

i am working on a cart system Plugin, i am setting a variable $cart in cart controller, and now i have to use the same variable in dish controller , how to do this? here is my code, i am working with:

Cart Controller:

    class CartsController extends CartAppController {

    public function view($cartId = null) {
            if (!empty($this->request->data)) {
                $this->CartManager->updateItems($this->request->data['CartsItem']);
            }

            if (!empty($cartId)) {
                $cart = $this->Cart->view($cartId, $this->Auth->user('id'));
            } else {
                $cart = $this->CartManager->content();
            }

            $this->request->data = $cart;
            $this->set('cart', $cart);    // This $cart variable is needed to be used in a different controller.
            $this->set('requiresShipping', $this->CartManager->requiresShipping());
        } 

}

Dish Controller

class DishesController extends AppController {
   public function index($id='') {
        **// here i need to print that **$cart** variable**
        $this->layout = false;
        $menu=$this->Menu->find('first', array('conditions' => array("Menu.id"=>$id),'limit'=>1));
        if(empty($id) || empty($menu)){
            $this->redirect(array('controller'=>'menus', 'action'=>'index'));
        }
        $dishes=$this->Dish->find('all', array('conditions' => array("Dish.status"=>"1", "Dish.menu_id"=>$id), 'limit'=>9, 'recursive'=>0, 'order' => array('Dish.id' => 'DESC')));
        $this->set('menu_name',$menu['Menu']['name']);
        $this->set('dishes',$dishes);
        $this->set('page_name','dishes');
    }

}

Any help would be appreciated :)

  • 写回答

1条回答 默认 最新

  • douyazi1129 2015-06-27 08:46
    关注

    Store your $cart data in the database and then store the record's primary key in a session called something like cart_id:-

    $this->Session->write('cart_id', $this->Cart->id);
    

    You can then get the cart from other controllers using the session data to retrieve it from the database:-

    $this->loadModel('Cart');
    $this->Cart->findById($this->Session->read('cart_id'));
    

    (Above is just an example and can be written much better depending on your particular needs.)

    This tends to be the way we approach an ecommerce site. I personally think it makes sense to store the data in the database and just keep the key in the session.

    评论

报告相同问题?

悬赏问题

  • ¥15 Python输入字符串转化为列表排序具体见图,严格按照输入
  • ¥20 XP系统在重新启动后进不去桌面,一直黑屏。
  • ¥15 opencv图像处理,需要四个处理结果图
  • ¥15 无线移动边缘计算系统中的系统模型
  • ¥15 深度学习中的画图问题
  • ¥15 java报错:使用mybatis plus查询一个只返回一条数据的sql,却报错返回了1000多条
  • ¥15 Python报错怎么解决
  • ¥15 simulink如何调用DLL文件
  • ¥15 关于用pyqt6的项目开发该怎么把前段后端和业务层分离
  • ¥30 线性代数的问题,我真的忘了线代的知识了