cakePHP中的Session使用

在cakePHP中的Session的使用场合有controller、view、component及helper中。不同的使用场合使用的方法也不一样。

  • 在控制器(controller)中使用
    <?php
    class AppController extends Controller {
      var $components = array('Session', 'Cookie');
      function login(){
        $this->Session->write('Account', $account);
        $this->Session->delete('Account');
        $this->Session->destroy();
      }
    }
    ?>
  • 在视图(view)中使用
    <?=$session->read('Account.username') ?>
  • 在组件(component)中使用
    <?php
    //通过组件的方式使用
    class P28nComponent extends Object {
        var $components = array('Session', 'Cookie');
        public function set($language=null){
          Configure::write('Config.language', $language);
          $this->Session->write('Config.language', $language);
          $this->Cookie->write('language', $language, null, '+1 day');
        }
    }
    //通过controller方式使用
    class P28nComponent extends Object {
        function initialize(&$controller) {
           $this->controller =& $controller;
        }
        public function set($language=null){
          Configure::write('Config.language', $language);
          $this->controller->Session->write('Config.language', $language);
          $this->controller->Cookie->write('language', $language, null, '+1 day');
          $this->controller->Session->setFlash(__('Please Select Language', true), 'default', array('class' => 'notice_msg_sm'));
        }
    }
    ?>
  • 在助手(helper)中使用
    <?php
    class AppHelper extends Helper {
      var $helpers = array('Html','Javascript', 'Session');
      function nav_menu(){
        $currentRole = $this->Session->read('Role.title');
      }
    }
    ?>

Monitor Your Web Site 24/7 - Receive email and SMS alerts anytime your web site goes down.

Related Posts

Leave a Reply

Monitor Your Web Site 24/7 - Receive email and SMS alerts anytime your web site goes down.

About Me

About Me
Record Technical Articles at Gooss.org.

Entries (RSS) and Comments (RSS). Valid XHTML and CSS and XFN.

© Copyright 2009 山海经. All rights reserved.

Social Bookmarks

Copyright © Designed by: Free WP Templates
Food Charts |  About Breast Milk |  Organic Food