Khanh Hoang - Kenn
Kenn is a user experience designer and front end developer who enjoys creating beautiful and usable web and mobile experiences.
Ắc hẳn khái niệm session khá quen thuộc đối với chúng ta .Trong bài viết này , tôi sẽ hướng dẫn các bạn cách sử dụng Sesion trong CakePHP kèm theo những ví dụ về cách sử dụng trong mỗi trường hợp
Trong CakePHP muốn lập trình ứng dụng thì ta cũng cần có những thành phần quan trọng như : Helper và Component thông qua hai biến $helpers và $component
Xem các viết các thành phần cho CakePHP tại đây
Ví dụ khai báo :
var $helpers = array('Html', 'Form','Javascript','Ajax','Common'); var $components = array('Acl',’Mail’);
Có những thành phần chỉ được khai báo trong $helpers như : Html,Form… , $component như : Acl,Mail.. . Tuy nhiên Session lại là trường hợp ngoại lệ , nó có thể khai báo trong cả hai thành phần $helpers và $components.
var $helpers = array('Html', 'Form','Javascript','Ajax','Common',’Session’); var $components = array('Acl',’Mail’,’Session’);
Cho dù Session được khai báo ở $helpers hay $component đi chăng nữa thì nó cũng có các hàm chính như sau :
a) write($name,$value)
- Lưu session có giá trị $value vào tên $name
- $name có thể sử dụng dấu chấm (.) để tạo thành mảng session
Ví dụ :
//Lưu theo cú pháp thông thường $this->Session->write('Username','administrator'); //Lưu dạng mảng $this->Session->write('Person.name', 'admin'); $this->Session->write('Person.email', '[email protected]');
b) read($name)
- Lấy giá trị của session thông qua tên
Ví dụ :
echo $this->Session->read('Username'); //kết quả admin pr($this->Session->read('Person')); //kết quả Array ( [name] => admin [email] => [email protected] )
c) check($name)
- Kiểm tra xem có tồn tại session có tên là $name hay không
Ví dụ: không tồn tại Session Username
$this->Session->check('Username'); //Kết quả false
d) delete($key)
- Xóa Session thông qua tên
//Xóa Session Username $this->Session->delete('Username'); //Chỉ xóa Session email của Person $this->Session->delete('Person.email'); //Xóa toàn bộ Session Person $this->Session->delete('Person');
e) destroy()
- Xóa toàn bộ Cookie và Session
$this->Session->destroy()
f) error()
- Xác định lỗi cuối cùng lên quan tới session
g) setFlash($message, $element = 'default', $params = array(), $key = 'flash')
- Thường sử trong Controllers
$message : nội dung hiển thị
$element : load file chứa nội dung bao quanh $message .Nội dung được lưu dạng file *.ctp trong thư mục app/view/elements/
$param : dủng dể thay đổi các thuộc tính như : class, id, style ..
$key : mặc định là “flash”
Ví dụ :
Tôi có file sms.ctp (app/views/elements/sms.ctp)
<div id="flashMessage" class="message_01"><?php echo $message ;?></div>
Thực hiện lệnh :
$this->Session->setFlash('I miss you all the time', 'sms', array('class' => 'message_02'))
Thì nội dung file sms.ctp sẽ được load và hiển thị là :
<div id="flashMessage" class="message_02">I miss you all the time</div>