Go to content Go to navigation Go to search

Sử dụng plugin chat trong cakephp 1.2

October 28th, 2009 by hoanbn

Xin chào các bạn!

Đây là môt plugin do tôi tự viết dựa trên các tính năng chat của livechat. Chương trình livechat tôi tham khảo được viết bằng php, để có thể quản trị được các chức năng tôi thấy có nhiều cái thừa  không cần thiết trong trường hợp của tôi. Tôi đã dựa vào livechat để viết plugin với tính năng tương tự. Plugin này có sử dụng jquery.

Các chức năng chính:

1)  Hiển thị danh sách người chat và danh sách người quản trị đang chat. Tôi tạm gọi là guests và operators.

2) Guest chỉ việc nhập tên và email, sau đó sẽ hiển thị màn hình chat. Operators sẽ thấy trạng thái chát của guest và bắt đầu chat. Một guest có thể do nhiều operators chat.

3) Operators sử dụng luôn bảng users.

3) Các chức năng hoặc động trong cửa sổ window riêng biệt (popup window).

Để sử dụng các bạn download plugin tại đây. (Để hểu rõ hơn về plugin bạn có thể tham khảo tại đây)

Cài đặt:

1) Đưa toàn bộ nội dung của plugin chat vào trong app/plugin

2) Bạn chạy file sqlChat trong thu mục app/plugins/chat/config/sql .

3) Copy file chat.ctp trong thu muc app/plugins/chat/views/layout vào trong thu mục app/views/layout.

Sử dụng:

Do các chức năng chat đểu hiển thị ra các cửa sổ riêng biệt. Do vậy ta chỉ việc tạo ra link gọi đến là ok.

Ví dụ:

<?php
//Hiển thị link để guest mở cửa sổ chat với admin
echo $html->link('Chat with Amdmin', '/chat/chats/form_guest', array('onclick' => "window.open('{$html->url('/chat/chats/form_guest')}','mywin','left=20,top=20,width=460,height=440,toolbar=0,resizable=0'); return false;"));
echo '<br />';
//Hiển thị link quản trị chat
echo $html->link('Manager chatting', '/chat/chats/chat_users', array('onclick' => "window.open('{$html->url('/chat/chats/chat_users')}','mywin','left=20,top=20,width=460,height=440,toolbar=0,resizable=0'); return false;"));
?>

Vậy là xong, chúc các bạn vui vẻ :D

Phân trang tìm kiếm đầy đủ với cakephp 1.2

July 24th, 2009 by hoanbn

Chào cả nhà!

Thật không nhớ nổi đây là lần thứ mấy tôi viết bài với tiêu đề phân trang tìm kiếm cho cakephp nữa. Vậy tại sao lại còn có bài viết này nữa. Việc phân trang tìm kiếm với cakephp đã không biết bao nhiêu lần làm tôi đâu đầu rồi. Sau nhiều lần tìm kiếm các giải pháp, nay tôi cũng đa tìm ra một giải pháp ứng ý trong việc tìm kiếm phân trang với cakephp. Sau đây tôi sẽ chia sẽ với mọi người giải pháp ấy, được minh họa thông qua ví dụ tìm kiếm sản phẩm dưới đây.

Việc đâu tiên là tôi phải tạo csdl. Trong ví dụ này tôi tạo csdl có tên là phantrang:

CREATE DATABASE phantrang;

CREATE TABLE IF NOT EXISTS `products` (
`id` int(4) NOT NULL AUTO_INCREMENT,
`name` varchar(255) DEFAULT NULL,
`model` varchar(255) NOT NULL,
`price` int(16) DEFAULT NULL,
`created` datetime DEFAULT NULL,
`type` enum(‘Loai 1′,’Loai 2′,’Loai 3′) DEFAULT NULL,
`description` text NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=MyISAM  DEFAULT CHARSET=latin1 AUTO_INCREMENT=5 ;

Vậy là tôi đã tạo xong CSDL, còn việc config để kết nối vào CSDL vừa tạo thì mọi người tự làm nhé. Dữ liệu trong đây thì mọi người tự thêm vào nhé.(^_^).

Công việc tiếp theo là tôi sẽ tạo ra một /app/controllers/products_controllers.php như sau:

/*  app/controllers/products_controller.php */

<?php
class ProductsController extends AppController {

var $name = ‘Products’;
var $scaffold;

}
?>

Với các chức năng như add, edit, delete trong ví dụ này tôi sẽ dùng chức năng scaffold của cakephp, và quả thật những trường hợp như thế này thì scaffold quá tuyệt vời. Trong bài viết này tôi sẽ chỉ chú trọng vào chức năng tìm kiếm mà thôi. Tiếp đến tôi sẽ tạo một function search trong products_controller như sau:

/*  app/controllers/products_controller.php */

<?php
class ProductsController extends AppController {

var $name = ‘Products’;
var $scaffold;

function search() {

}

}
?>

Cả nhà chú ý nhé, khi tôi thêm dữ liệu vào thì tôi sẽ copy lại nguyên nội dung của cả trang để mọi người dễ hiểu hơn, chỉ phần nào thêm mới tôi sẽ in đậm lên thôi. Bây giờ tôi sẽ tạo một trang view search như sau app/views/products/search.ctp

//  app/view/products/search.ctp

<?php
echo $form->create(‘Search’, array(‘url’ => ‘/products/dataSearch’));
echo $form->input(‘name’);
echo $form->input(‘price’);
echo $form->input(‘model’);
echo $form->input(‘type’, array(‘options’ => array(” => ”,’Loai 1′ => ‘Loại 1′, ‘Loai 2′ => ‘Loại 2′, ‘Loai 3′ => ‘Loai 3′)));
echo $form->input(‘description’);
echo $form->end(‘Search’);

?>

Phần form search vừa rồi tôi đã đề ‘url’ trỏ đến action ‘dataSearch’. Action ‘dataSearch’ này trong đây sẽ thực hiện công việc xử lý dữ liệu trong form tìm kiếm và chuyển lên url. Tôi thêm function dataSearch trong products_controller như sau:

/*  app/controllers/products_controller.php */

<?php
class ProductsController extends AppController {

var $name = ‘Products’;
var $scaffold;

function search()
{
}

function dataSearch()
{
// the page we will redirect to
$url['controller'] = ‘products’;
$url['action'] = ’search’;

// build a URL will all the search elements in it
// the resulting URL will be
// example.com/cake/posts/index/Search.keywords:mykeyword/Search.tag_id:3
foreach ($this->data as $k=>$v){
foreach ($v as $kk=>$vv){
$url[$k.'.'.$kk]=$vv;
}
}

// redirect the user to the url
$this->redirect($url, null, true);
}

}
?>

Hàm dataSearch sẽ thực hiện chức năng chuyển tòan bộ dữ liệu vừa được gửi (submit) vào trong một mảng và sau đó thông qua hàm ‘redirect’ chuyến sang một trang mới. Việc chuyển đến trang nào sẽ được quyết định thông qua 2 biến “$url['controller']” và “$url['action']” . Nếu bạn nào chưa hiểu hàm này thực hiện những công việc gì thì các bạn cũng không cần tìm hiểu đâu, vì hàm này sẽ không bào giờ thay đổi cả, chỉ cần thay đổi giá trị 2 biến đó thôi. Cả nhà có thể tạm hiểu là hàm này thực hiện việc chuyển tất cả dữ liệu được submit lên trên url.

Vậy là sau khi hàm dataSearch xử lý xong, sẽ chuyển dữ liệu về action “search” trong products_controller. Lúc này sẽ tồn tại một biến mảng “$this->passedArgs” chứa dữ liệu của trang search khi submit. Hay nói đúng hơn biến “$this->passedArgs” chứa các dữ liệu được truyền ở phía trên url và đưa vào thành các mảng tương ứng. Ta sẽ xử lý dữ liệu truyền vào để tạo điều kiện lọc như sau:

/*  app/controllers/products_controller.php */

<?php
class ProductsController extends AppController {

var $name = ‘Products’;
var $scaffold;

function search()
{
$conditions = array();
if (!empty($this->passedArgs))
{
if (isset($this->passedArgs['Search.name']))
{
$conditions[]["Product.name LIKE"] = “%{$this->passedArgs['Search.name']}%”;
$this->data['Search']['name'] = $this->passedArgs['Search.name'];
}

if (isset($this->passedArgs['Search.price']))
{
$conditions[]["Product.price "] = $this->passedArgs['Search.price'];
$this->data['Search']['price'] = $this->passedArgs['Search.price'];
}

if (isset($this->passedArgs['Search.model']))
{
$conditions[]["Product.model"] = $this->passedArgs['Search.model'];
$this->data['Search']['model'] = $this->passedArgs['Search.model'];
}

if (isset($this->passedArgs['Search.type']))
{
$conditions[]["Product.type"] = $this->passedArgs['Search.type'];
$this->data['Search']['type'] = $this->passedArgs['Search.type'];
}
}

$this->paginate = array(‘limit’ => ‘1′, ‘order’ => ‘Product.created DESC’);
$this->set(‘products’, $this->paginate(‘Product’, $conditions));

}

function dataSearch()
{
// the page we will redirect to
$url['controller'] = ‘products’;
$url['action'] = ’search’;

// build a URL will all the search elements in it
// the resulting URL will be
// example.com/cake/posts/index/Search.keywords:mykeyword/Search.tag_id:3
foreach ($this->data as $k=>$v){
foreach ($v as $kk=>$vv){
$url[$k.'.'.$kk]=$vv;
}
}

// redirect the user to the url
$this->redirect($url, null, true);
}
}
?>

Trong phần controller này ta sẽ thưc hiện phân trang như bình thường trong cakephp, chỉ khác là sẽ có thêm điều kiện tìm kiếm như ở phía trên thôi.

Việc tiếp theo sẽ là hiển thị kết quả tìm kiếm ra trang search. Ta sẽ thêm vào view search như sau:

/*  app/views/products/search.ctp */

<?php
echo $form->create(‘Search’, array(‘url’ => ‘/products/dataSearch’));
echo $form->input(‘name’);
echo $form->input(‘price’);
echo $form->input(‘model’);
echo $form->input(‘type’, array(‘options’ => array(” => ”,’Loai 1′ => ‘Loại 1′, ‘Loai 2′ => ‘Loại 2′, ‘Loai 3′ => ‘Loai 3′)));
echo $form->input(‘description’);
echo $form->end(‘Search’);

?>

<?php
echo $paginator->counter(array(
‘format’ => ‘Page %page% of %pages%, showing %current% records out of
%count% total, starting on record %start%, ending on %end%’
));
?>
<table cellpadding=”1″ cellspacing=”0″>
<tr>
<th>ID</th>
<th>Name</th>
<th>Model</th>
<th>Price</th>
<th>Created</th>
<th>Type</th>
<th>Description</th>
</tr>
<?php
foreach ($products as $product)
{
?>
<tr>
<td><?=$product['Product']['id']?></td>
<td><?=$product['Product']['name']?></td>
<td><?=$product['Product']['model']?></td>
<td><?=$product['Product']['price']?></td>
<td><?=$product['Product']['created']?></td>
<td><?=$product['Product']['type']?></td>
<td><?=$product['Product']['description']?></td>
</tr>
<?php
}
?>
</table>

<!– Shows the next and previous links –>

<?php
$paginator->options(array(‘url’ => $this->passedArgs));
echo $paginator->prev(‘« Previous ‘);
echo $paginator->numbers();
echo $paginator->next(‘ Next »’);
?>

Trong phần view trên thì dòng quan trọng nhất chính là “$paginator->options(array(‘url’ => $this->passedArgs));”. Dòng này có tác dụng là sẽ truyền toàn bộ các tham số trong mảng “$this->passedArgs” lên trên url của các link phân trang trong cake. Như vậy có nghĩa là các điều kiện tìm kiếm sẽ vẫn còn khi mọi người chuyển trang. Vậy là tôi đã thực hiện xong việc phân trang tìm kiếm trong cakephp1.2 rồi. Mọi người vào đọc thấy có gì thấy khó hiểu thì comment vào nhé. Tôi sẽ sửa lại cho dễ hiểu hơn.

Chúc cả nhà vui vẻ với cakephp nhé.


Hướng dẫn làm web cơ bản với CakePHP

July 1st, 2009 by tungnd

CakePHP là 1 trong số nhiều framework dành cho PHP. Ở đây, chúng tôi chọn CakePHP vì đó là 1 công cụ thân thiệt, dẽ sử dụng, nhanh, mạnh và rất linh hoạt. Để có thể học và sử dụng thành thạo 1 cách nhanh chóng bạn phải biết những kiến thức cơ bản về HTML và PHP.

Bây giờ ta bắt đầu thôi nhỉ, đầu tiên bạn phải download CakePHP về : Download

Cài Đặt :

Để có thể sử dụng  framework vừa download về, máy tính của bạn phải đáp ứng thêm 1 số yêu cầu sau :

- Một HTTP server (Apache, ISS). Ở đây tôi sử dụng Xampp vì nó khá phổ thông và còn kèm thêm cho bạn MySQL.

-Database : Cake hỗ trợ các hệ cơ sở dữ liệu sau : MySQL, PostgreSQL.

- Chú ý thêm là CakePHP chỉ support trong PHP ver4 trở lên.

Sau khi download thành công và đáp ứng đủ các yêu cầu trên thì bạn có thể giải nén tập tin (.zip) vừa download về và sao chép vào thư mục chứa Apache server (vd :  C:\AppServ\www\CakePHP).

Cấu Hình :

Đầu tiên, để Cake và DataBase hoạt động cùng nhau, bạn phải cấu hình lại file database.php :

-Mở file database.php.default tại /CakePHP/app/config/database.php.default

-Điều chỉnh lại các thông số liên quan :

var $default = array( 'driver' => 'mysql', 'connect' => 'mysql_connect', 'host' => 'localhost', 'login' => 'user', 'password' => 'password', 'database' => 'project_name', 'prefix' => '' );

Với user, password, database lần lượt là: tên user, password và database ở trong MySql. Quy ước về đặt tên bảng trong database

  • Tên bảng trong cake nên ở dạng tiếng Anh số nhiều (vd: users, customers, students, … )
  • Bảng phải có primary key tên là ‘id’
  • Nếu có sử dụng quan hệ trong các bảng vd: user_id (user không có s và dấu _ cộng id)

-Tiếp đến bạn thay đổi tên file thành database.php -Cuối cùng, mở file core.php tại /CakePHP/app/config/core.php. Thay đổi security theo ý của bạn : Configure::write(‘Security.salt’, ‘8rnc4ry438tc34jchcyu34cu5cbn4u’);  => Configure::write(‘Security.salt’, ‘<tùy bạn>’);

Hướng dẫn sử dụng :

Để kiểm tra xem khâu cài đặt có hoàn thành hay không, bạn mở đường dẫn :  http://localhost/CakePHP/ Ở đây tôi không tiện chụp ảnh lại nên bạn chịu khó nhìn giao diện, nếu không thấy đỏ lòm hay vàng khè j` thì cứ yên tâm là đã ok ! Yên tâm hơn nữa thì hãy tìm 2 dòng Your database configuration file is present.  và Cake is able to connect to the database. Nếu tìm tháy thì cùng tôi bắt đầu tiếp. Còn nếu có 2 màu đặc biệt đấy thì bạn nên xem lại các bước đã làm ! Tạo bảng Cơ Sở Dữ Liệu : tạo bảng customers như sau :

id: INT, AUTO_INCREMENT, PRIMARY KEY
name: NVARCHAR
age: INT
address: VARCHAR

Code :

Quên mất, bạn đã biết mô hình MVC (Models-Controller-View) là j` chưa nhỉ, nếu chưa thì bạn cứ hiểu nôm na như sau : Mô hình MVC trong lập trình hướng đối tượng hoạt động theo 3 tầng, tầng trên cùng là View, tiếp theo là Controller và tầng dưới cùng là Models.

- Models : dùng để giao tiếp với Cơ Sở Dữ Liệu của bạn.

-Controller : dùng để tạo các function để viết các yêu cầu theo ý muốn, lấy dữ liệu từ Cơ Sở Dữ Liệu thông qua Models và hiển thị ra tại View.

-View : là nơi thể hiện dữ liệu đã được xử, hoặc từ đây ta có thể nhập dữ liệu mới, sau đó Controller sẽ lấy dự liệu từ View chuyển về cho Models để lưu vào Cơ Sở Dữ Liệu. Nói nhanh cho vuông thì View cũng có thể coi là 1 trang template.

*Để hiểu thêm về mô hình MVC thì bạn hãy search google và tìm hiểu thêm, còn bây giờ tôi phải vào mục chính là làm việc với CakePHP.

Chúng ta bắt đầu làm việc theo thứ tự 3 tầng MVC từ thấp đến cao.

Đâu tiên là Model : mở trình soạn, tạo file customer.php tại \CakePHP\app\models\customer.php

<?php
class Customer extends AppModel
{
   var $name = 'Customer';
}
?>

Tiếp đến là Controller : tạo file custermers_controller.php tại \CakePHP\app\controllers\custermers_controleller.php

<?php
class CustomersController extends AppController
{
    var $name = 'Customers';
    function index()
    {
        $this->set('customers', $this->Customer->findAll());
    }
}
?>

Cuối cùng là View : file index.ctp tại \CakePHP\app\view\custermers\index.ctp

<h1>Customer Manager</h1>
   <table>
       <tr>
           <th>Id</th>
           <th>Name</th>
           <th>Age</th>
           <th>Address</th>
       </tr>
       <?php foreach ($customers as $cust): ?>
       <tr>
           <td><?php echo $cust['Customer']['id']; ?></td>
           <td>
               <?php echo $html->link($cust['Customer']['name'], '/customers/view/'.$cust['Customer']['id']);?>
               <?php echo $html->link('Delete',"/customers/delete/{$cust['Customer']['id']}",null,'Are you sure?')?>
               <?php echo $html->link('Edit', '/customers/edit/'.$cust['Customer']['id']);?>
           </td>
           </td>
           <td><?php echo $cust['Customer']['age']; ?></td>
           <td><?php echo $cust['Customer']['address']; ?></td>
       </tr>
       <?php endforeach; ?>
   </table>

Có vẻ ổn rồi, bạn hãy thử mở đường dẫn http://localhost/CakePHP/custermers để xem kết quả của chương trình bạn vừa viết. Và sau đó tìm hiểu thêm nhiều tính năng nữa của Cake nhé, khi đó bạn sẽ rất “sướng” cho mà xem.

Còn tôi thì phải đi làm tách trà đá cái đã !







Sự tàn lụi của PHP

April 29th, 2009 by hoangnd

Mặc định rằng các bạn đang đọc bài này là những người làm trong ngành nên tôi sẽ không giải thích hay ghi chú những khái niệm phổ thông. Mặt khác, lý lẽ trong bài viết này chỉ phản ánh quan điểm của cá nhân tôi, không đại diện cho ai hay tổ chức nào khác.

Lịch sử ngành công nghiệp máy tính & mạng đã chứng minh PHP là một trong số những ngôn ngữ mạnh & linh động nhất trên nền Web và cũng không quá khó để thành thục ở mức phổ thông. Được phát triển và biết đến từ những năm cuối của thập kỷ trước, PHP đã đạt được sự tăng trưởng đáng kinh ngạc so với các ngôn ngữ lập trình khác.

 

PHP Timeline

PHP Timeline

 

 

Nhìn biểu đồ trên, ta thấy con đường đi lên của PHP là theo hướng phát triển truyền thống, tức là Thiết kế -> sử dụng -> chỉnh sửa -> lớn mạnh -> phát triển. Điều thú vị là cho đến nay, rất nhiều các sản phẩm được phổ biến rộng rãi cũng đi theo con đường trên như các nền tảng .NET, Java hay Linux.

Ta lần lượt điểm qua một số điểm mẫu chốt sau

Vòng đời

Một lần nữa, nhắc lại thế mạnh của PHP trên nền web chính là tốc độ (phát triển & thực thi), nhẹ & dễ học. Bên cạnh đó, do đặc tính mã nguồn mở (theo giấy phép PHP) cũng như sự đổi mới về phong cách khi ra đời, PHP sở hữu rất nhiều thứ quý giá

 

  • Cộng đồng lớn. Khoản này vô đối. Luôn có những guru sẵn sàng chia sẻ kinh nghiệm & kiến thức, hướng dẫn những người mới và giải đáp thắc mắc.
  • Thư viện, cả nội tại và mở rộng của PHP, có chứa số lượng function cực lớn được đóng góp bởi những người tình nguyện. Con số vào khoảng 700 buit-in functions và uncountable external functions (hoangnd tính toán).
  • Framework đa dạng về số lượng cũng như chất lượng, thậm chí đa dạng cả về mô hìnhmục đích sử dụng.

 

Sự mở rộng và phát triển

 

  • Khái niệm về namespace. .NET đã có từ lâu, Java cũng có khái niệm package gần tương đương, và bây giờ chúng ta chứng kiến PHP. Đành rằng namespace ra đời với mục đích cơ bản là giúp lập trình viên dễ tổ chức và quản lý code hơn, nhưng với PHP thì tôi cho rằng là một sự ôm đồm. Mặc dù có rất nhiều những giải thích về cách gõ namespace trong PHP, nhưng thực sự là rất khó chấp nhận ký tự “\” để phân cách.  Thứ nhất  là hơi va chạm với tư tưởng chạy đa nền của PHP vì ký tự “\” được dùng phổ biến trong windows để phân tách đường dẫn. Thứ hai là có vẻ như PHP đã sử dụng cạn kiệt tài nguyên bàn phím. 
  • PHP cho đến nay đã quá rộng lớn và các lập trình viên dễ dàng tìm được nhiều giải pháp khác nhau cho cùng một bài toán. Điều này thể hiện rất rõ ràng tư tưởng “open and share” mà nhờ nó, nhân loại mới có được kho tri thức khổng lồ (không chỉ trong ngành khoa học máy tính mà còn ở tất cả các lĩnh vực khác). Tuy nhiên, hãy nhìn Python làm, bạn có rất ít những cách để xử lý một vấn đề và thường thì những cách đó luôn là cách tốt nhất và dễ dàng nhất cho bạn, đến nỗi bạn chả buồn nghĩ tới hướng khác :P . Ở phía đối diện, .NET độc quyền gắn chặt với hệ điều hành Window$ của Micro$oft nhưng có sự thống nhất, rõ ràng và ổn định cực tốt (nếu bạn chọn phát triển trên nền tảng này).

 

Yahoo và facebook xài PHP

Quá đúng, bỏ qua phần backend thì chính những đoạn mã  PHP đã dựng lên bộ mặt yahoo & facebook như bây giờ. Và nó đã chứng minh giá trị của mình khi cả Yahoo & facebook đều đã hoặc đang trở thành những đế chế internet với danh tiếng, lợi nhuận & lượng người dùng cực lớn, chưa kể đến số lượng các dịch vụ kèm theo.

Thế nhưng, trong các đăng báo tuyển dụng, họ luôn muốn ưu tiên những ứng viên biết thêm Perl hoặc Python bên cạnh thành thạo PHP (bỏ qua các yêu cầu khác). Câu hỏi đặt ra là, họ (yahoo & facebook) định cho những ứng viên này làm cả ở nền tảng trên & dưới của hệ thống web application? hay họ muốn những ứng viên đó có được tư duy ngôn ngữ của perl, python? hay nữa là họ muốn dự phòng và sẵn sàng chuyển đổi sang perl, python? (lol)

Đặc điểm

Một chút hình dung


Có nghĩa lý gì? Ai cũng biết .NET là một nền tảng còn PHP là một ngôn ngữ lập trình, tất nhiên sẽ là không hợp lý nếu so sánh chúng với nhau. Cái tôi muốn đề cập là, với .NET chúng ta có thể sử dụng để lập trình web, windows application, mobile, embedded, cloud … với sự tách biệt không quá lớn dành cho lập trình viên (tất nhiên môi trường triển khai thì không nói). Còn PHP không thể đứng một mình, nó sẽ kết hợp với các công nghệ khác tạo thành những nền tảng thực thi bài toán, mà chất lượng kết quả bài toán đó phụ thuộc rất nhiều vào kinh nghiệm & kiến thức của kiến trúc sư trưởng dự án. Sợi dây liên kết này tôi cho rằng là kém vững trãi hơn so với .NET

Ngoài ra, mô hình trên còn thể hiện một nội dung khác. Nếu coi mỗi ngôn ngữ là một tập thông tin thì chúng liên kết với nhau qua giao của những tập đó. Có nghĩa là PHP sẽ đứng chung với python, perl, ruby … Và cũng có nghĩa là tôi sẽ chọn python thay vì PHP để kết hợp với flex. Tức là PHP đã mất đi một người dùng là tôi, ít nhất là trong dự án nào đó.

Buồn ngủ quá nên đoạn này viết hơi sơ sài và lung tung, sẽ cập nhật lại sớm thôi

Tuy nhiên

Các lập trình viên PHP đừng quá buồn và suy nghĩ nhiều làm gì, PHP đã, đang và sẽ luôn làm rất tốt trong phân khúc thị trường của nó. Và trong 1, 2, 3 năm nữa có thể ta có PHP phiên bản 6.0, 6.1, 6.2 … nhưng rồi nó sẽ phát triển tiếp thành cái gì? Cộng đồng không có nhiều người biết, tôi cá là bạn không biết, còn tất nhiên là tôi không biết roài. :D

(just my cent at 3 a.m)

Cakephp 1.2 – một số hàm hepler thường dùng (Phần 2)

January 18th, 2009 by hoanbn

Sau đây sẽ là một số hàm hepler thường dùng trong form:

8. form->input: Tạo ra thẻ html input

Cú pháp:
$form->input(string $fieldName, array $options = array()) ;

Thẻ input trong cakephp là thẻ được sử dụng nhiều nhất, hiệu quả nhất và phức tạp nhất trong hepler form của cakephp. Trước tiên ta hãy tìm hiểu cách sinh ra các phương thức tự động trong Formhepler.
a.  Quy cách sinh tự động các thẻ HTML.
Thẻ input sẽ dựa vào loại dữ liệu (type) của model để tự động sinh ra các thẻ html tương ứng. Sau đây là một bảng liệt kê các thẻ html trả về tương ứng với loại dữ liệu:

Kiểu dữ liệu Thẻ form trả về
string (char, varchar, etc.) text
boolean, tinyint(1) checkbox
text textarea
text, with name of password, passwd, or psword password
date day, month, and year selects
datetime, timestamp day, month, year, hour, minute, and meridian selects
time hour, minute, and meridian selects

Cho ví dụ, giả sử model User bao gồm các trường là username(varchar), password(varchar), approved(datetime) và quote(text). Chúng ta có thể chỉ sử dụng một phương thức input trong FormHepler là có thể tạo ra được tất cả các thẻ html khác nhau.
Ví dụ:

<?php echo $form->create(); ?>

<?php
echo $form->input('username');   //text
echo $form->input('password');   //password
echo $form->input('approved');   //day, month, year, hour, minute, meridian
echo $form->input('quote');      //textarea
?>

<?php echo $form->end('Add'); ?>

Ta cũng có thể mở rộng một vài thuộc tính trong thẻ input như sau:

echo $form->input('birth_dt', array( 'label' => 'Date of birth' , 'dateFormat' => 'DMY' , 'minYear' => date('Y') - 70, 'maxYear' => date('Y') - 18 ));

b. Quy ước tên trường trong phương thức input
Form hepler rất thông minh, khi bạn xác định tên một trường với phương thức của form helper, cakephp sẽ tự động sử dụng tên model hiện đại để dịnh dạng theo cấu trúc dưới đây.
<input type=”text” id=”ModelnameFieldname” name=”data[Modelname][fieldname]“>


Bạn cũng có thể chỉ ra tên model bằng truyển tên model như tham số đầu tiên (Modelname.fieldname).
<?php echo $form->input(‘Modelname.fieldname’); ?>
Trong trường hợp bạn muốn sử dụng nhiều tên trường giống nhau, chúng ta có thể tạo ra một mảng array và lưu chúng vào CSDL bằng phương thức saveAll() theo quy ước như ví dụ sau:

<?php
echo $form->input('Modelname.0.fieldname');
echo $form->input('Modelname.1.fieldname');
?>
//Dữ liệu trả về HTML
<input type="text" id="Modelname0Fieldname" name="data[Modelname][0][fieldname]">
<input type="text" id="Modelname1Fieldname" name="data[Modelname][1][fieldname]">

c. Các options trong thẻ input ($options)
c.1. $options['type']
Bạn có thể chỉ định loại của thẻ input tạo ra giống như trong html. Type sẽ được gán hợp lệ như sau: file, password, text, textarea ….

Ví dụ:

<?php echo $form->input('field', array('type' => 'file')); ?>
//Dữ liệu trả về HTML
<div class="input">
<label for="UserField">Field</label>
<input type="file" name="data[User][field]" value="" id="UserField" />
</div>

c.2. $options['options']
Từ khóa này sẽ tạo ra cho bạn một thẻ select input hoặc một thẻ radio group. Nếu muốn sử dụng với thẻ radio, bạn phải dùng thêm $option['type']. Mặc định sẽ tạo ra một thẻ select input. (Lưu ý: từ khóa options sẽ luôn được gán với một mảng array)
Ví dụ:

<?php echo $form->input('field', array('options' => array(1,2,3,4,5))); ?>
//Dữ liệu trả về HTML
<div class="input">
<label for="UserField">Field</label>
<select name="data[User][field]" id="UserField">
<option value="0">1</option>
<option value="1">2</option>
<option value="2">3</option>
<option value="3">4</option>
<option value="4">5</option>
</select>
</div>

Bạn cũng có thể sử dụng cặp key-value như sau:

<?php echo $form->input('field', array('options' => array(
'Value 1'=>'Label 1',
'Value 2'=>'Label 2',
'Value 3'=>'Label 3'
))); ?>
//Dữ liệu trả về HTML
<div class="input">
<label for="UserField">Field</label>
<select name="data[User][field]" id="UserField">
<option value="Value 1">Label 1</option>
<option value="Value 2">Label 2</option>
<option value="Value 3">Label 3</option>
</select>
</div>

c.3. $options['multiple']
Nếu ‘mutiple’ được gán là true cho một thẻ input mà đầu ra là thẻ select input, thì bạn sẽ có thể lựa chọn nhiều tùy chọn selection cùng một lúc.
Ví dụ:

$form->input('Model.field', array( 'type' => 'select', 'multiple' => true ));

c.4. $options['maxLenght']
Xác định số ký tự cho phép nhập vào trong một thẻ text input.

c.5. $options['label']
Gán nhãn cho một thẻ input khi thẻ đó được hiển thị
Ví dụ:

<?php echo $form->input( 'User.name', array( 'label' => 'The User Alias' ) );?>
//Dữ liệu trả về dạng HTML
<div class="input">
<label for="UserName">The User Alias</label>
<input name="data[User][name]" type="text" value="" id="UserName" />
</div>

Chúng ta cũng có thể gán key label là false nếu không muốn hiển thị nhãn label trong thẻ
Ví dụ:

<?php echo $form->input( 'User.name', array( 'label' => false ) ); ?>
//Dữ liệu trả về dạng HTML
<div class="input">
<input name="data[User][name]" type="text" value="" id="UserName" />
</div>

c.6. $options['id']
Gán giá trị DOM id của một thẻ input.

c.7. $options['default']
Sử dụng kết hợp với thẻ select input. Gán một giá trị là defaul trong tập hợp các tùy chọn đó khi hiển thị .
Ví dụ;

<?php echo $form->input('country', array('options'=>$countries, 'default'=>'US')); ?>

c.8. $options['empty']
Khi sử dụng với thẻ select list, một thẻ option với giá trị rỗng trong list chọn của thẻ input. Nếu muốn có một giá trị rỗng trong option, ta chỉ việc truyển giá trị rỗng.
Ví dụ:

<?php echo $form->input('field', array('options' => array(1,2,3,4,5), 'empty' => '(choose one)')); ?>
//Dữ liệu trả về dạng HTML
<div class="input">
<label for="UserField">Field</label>
<select name="data[User][field]" id="UserField">
<option value="">(choose one)</option>
<option value="0">1</option>
<option value="1">2</option>
<option value="2">3</option>
<option value="3">4</option>
<option value="4">5</option>
</select>
</div>
9. form->hidden: Tạo ra một thẻ input hidden

Cú pháp
$form->hidden(string $fieldName, array $options)
Ví dụ:

<?php echo $form->hidden('field', array('id' => 'field')); ?>
//Dữ liệu trả về HTML
<input type="hidden" name="data[ModelName][field]" id="field" />
10. form->password: Tạo ra một thẻ input dạng password

Cú pháp:
$form->password(string $fieldName, array $options);
Ví dụ:

<?php echo $form->password('pass', array('id' => 'pass')); ?>
//Dữ liệu trả về HTML
<input type="password" name="data[ModelName][pass]" id="pass" />
11. form->text: Tạo ra một thẻ input text

Cú pháp:
$form->text(string $fieldName, array $options);
Ví dụ:

<?php echo $form->text('field', array('id' => 'field')); ?>
//Dữ liệu trả về HTML
<input type="text" name="data[ModelName][field]" id="field" />
12. form->textarea: Tạo ra một thể input textarea

Cú pháp:
$form->textarea(string $fieldName, array $options)
Ví dụ

<?php echo $form->textarea('field', array('id' => 'field')); ?>
//Dữ liệu trả về HTML
<textarea name="data[ModelName][field]" id="field" />
13. form->submit: Tạo ra một nút submit

Cú pháp:
$form->submit(string $caption, array $options)
Tạo ra một nút button submit với nhãn là $captió. Nếu $caption là một URL của một image, thì nút submit sẽ hiện thị như một images.
Ví dụ:

<?php echo $form->submit('save', array('id' => 'field')); ?>
//Dữ liệu trả về HTML
<button type="submit" name="data[ModelName][save]" id="field" />
14. form->checkbox: Tạo ra một thẻ checkbox

Cú pháp:
$form->checkbox(string $fieldName, array $options)
Tạo ra một thẻ checkbox. Phương thức này cũng sẽ tạo ra một thẻ input hidden ẩn để phục vụ gửi dữ liệu lên.
Ví dụ

<?php echo $form->checkbox('done'); ?>
//Dữ liệu trả về dạng HTML
<input type="hidden" name="data[ModelName][done]" value="0" id="UserDone_" />
<input type="checkbox" name="data[ModelName][done]" value="1" id="UserDone" />
15. form->radio: tạo ra một thẻ radio button.

Cú pháp:
$form->radio(string $fieldName, array $options, array $attributes)
Tạo ra một thẻ radio button input. $attributes['value'] để gán giá trị được set mặc định. Thuộc tính radio sẽ tạo ra một label và fieldset với giá trị mặc định, nếu muốn thay đổi thì gán $attributes['legend'] là false.
Ví dụ:

<?php echo $form->radio('User.sex', array(0 => 'male', 1 => 'female'), array('value' => '1')); ?>
//Dữ liệu trả về dạng html
<fieldset>
<legend>Sex</legend>
<input type="radio" name="data[User][sex]" id="UserSex0" value="0"  />
<label for="UserSex0">male</label><input type="radio" name="data[User][sex]" id="UserSex1" value="1" checked="checked"  />
<label for="UserSex1">female</label>
</fieldset>
16. form->select: tạo ra  một thẻ select

Cú pháp:
$form->select(string $fieldName, array $options, mixed $selected, array $attributes, boolean $showEmpty)


Tạo ra một thẻ input select, với các item nằm trong $options, với tùy chọn $selected ta có thẻ chọn một item mặc định được chọn. Với giá trị $showEmpty gán là false, nếu muốn hiện ra một lựa chọn với giá trị trống làm mặc định.
Ví dụ:

<?php echo $form->select('age', array(0 => 'male', 1 => 'female'), '1'); ?>
//Dữ liệu trả về HTML
<select name="data[age]" id="age">
<option value=""></option>
<option value="0">male</option>
<option value="1" selected="selected">female</option>
</select>
17. form->file: Tạo ra một thẻ input file

Cú pháp:
$form->file(string $fieldName, array $options)
Ví dụ:

<?php echo $form->file('fileName', array('id' => 'fileName')); ?>
//Dữ liệu trả về dạng HTML
<input type="file" name="data[fileName]" id="fileName" value="" />
18. form->submitImage: Tạo ra một nút button submit ảnh

Cú pháp:
$form->submitImage(string $path, array $options);
Tạo ra một nút button submit ảnh theo đường chỉ định URL trong $path

Ví dụ:

<?php echo $form->submit('anh.jpg', array('id' => 'anh1')); ?>
//Dữ liệu trả về dạng HTML
<div class="submit"><input type="image" src="/projectName/img/anh.jpg" id="anh1" /></div>

(Chú ý: Tất cả các phương thức được giới thiệu từ phần 9 trở đi đều có thể dùng phương thức input ở phần 8 thay thế được)

Cakephp 1.2 – một số hàm hepler thường dùng (Phần 1)

January 17th, 2009 by hoanbn

Với các bạn đã từng làm việc với cakephp hẳn các bạn không lạ gì việc sử dụng các hepler trong cake như form, html, javascript. Sau đây tôi xin liệt kê một số hàm hay sử  dụng nhất trong cakephp, cấu trúc và cách sử dụng chúng.

1. javascript->link:Chỉ link đường dẫn tới file javascript
Cú pháp:

$javascript->link($url, $inline);

$url (require): đường dẫn tới file javascript. Các file javascript sẽ được đặt trong thư mục ‘app/webroot/js’. Mặc định url là đường dẫn tới thư mục app/webroot/js/.

$inline: (boolean) . Nếu giá trị là true, thì thẻ script sẽ được in trong thẻ header , nếu là false thì sẽ in trong $script_for_layout. Giá trị mặc đinh là true.

Ví dụ:
<?php echo $javascript->link('script.js', true); ?>
//Dữ liệu trả về html
<script type="text/javascript" src="/test/js/script.js"></script>
2. html->css:link chỉ đường dẫn tới một file css
Cú pháp:

$html->css(mixed $path, string $rel = null, array $htmlAttributes = array(), boolean $inline = true);

Tạo một link tới file css. Nếu $inline được gán là false, thì thẻ css sẽ được đặt bên trong biến $script_for_layout, còn là true thì đặt trong thẻ header. Mặc định đường dẫn trong của file css là /app/webroot/css/.

Ví dụ:
<?php echo $html->css('forms'); ?>
//Dữ liệu trả về html
<link rel="stylesheet" type="text/css" href="/test/css/forms.css" />

//Ta cũng có thể khai báo nhiều file css cùng một lúc
<?php echo $html->css(array('forms','tables','menu')); ?>
//Dữ liệu trả về html
<link rel="stylesheet" type="text/css" href="/test/css/forms.css" />
<link rel="stylesheet" type="text/css" href="/test/css/tables.css" />
<link rel="stylesheet" type="text/css" href="/test/css/menu.css" />
3. html->image: Link đường dẫn tới một file ảnh
Cú pháp:

$html->image(string $path, array $htmlAttributes = array());

Tạo ra một thẻ định dạng là image. Mặc định nó sẽ chỉ tới thư mục /app/webroot/img/

Ví dụ:
<?php echo $html->image('cake_logo.png', array('alt' => 'CakePHP'))?>
//Dữ liệu trả về html
<img src="/img/cake_logo.png" alt="CakePHP" />
4. html->link: Tạo ra một thẻ html link.
Cú pháp:

$html->link(string $title, mixed $url = null, array $htmlAttributes = array(), string $confirmMessage = false,boolean $escapeTitle = true);


Tạo ra một thẻ html link. Các tham số truyền vào là
$title: Nhãn của đường link.
$url: Đường dẫn của link liên kết.
$htmlAttributes: các thuộc tính html của thẻ link.
$confirmMessage: Thông báo khi kích vào link. Mặc định giá trị là false.

Ví dụ:
<?php echo $html->link('Enter', '/pages/home', array('class'=>'button')); ?>
//Dữ liệu trả về HTML
<a href="/pages/home" class="button">Enter</a>

<?php echo $html->link('Delete', array('controller'=>'recipes', 'action'=>'delete', 6), array(), "Are you sure you wish to delete this recipe?");?>
//Dữ liệu trả về html
<a href="/recipes/delete/6" onclick="return confirm('Are you sure you wish to delete this recipe?');">Delete</a>

//Chuỗi query cũng có thể tạo ra từ một thẻ link()
<?php echo $html->link('View image', array('controller' => 'images', 'action' => 'view', 1, '?' => array( 'height' => 400, 'width' => 500))); ?>
//Dữ liệu trả về html
<a href="/images/view/1?height=400&width=500">View image</a>
5. html->url: Tạo ra đường dẫn tới link hiện tại
Cú pháp:

$html->url($path);

Ví dụ:
//Giả sử ta đang trong project test

<?php echo $html->url('cake.jpg'); ?>
//Dữ liệu trả về html
'/test/cake.jpg'
<?php echo $html->url('/file.txt'); ?>
//Dữ liệu trả về html
/test/file.txt
6. form->create: Tạo ra một thẻ form mở
Cú pháp:

$form->create(string $model = null, array $options = array());

Tất cả các tham số có thể là tùy chọn. Nếu không có tham số truyền vào, thì mặc định phương thức là POST, và controller và action nào gọi ra view chứa form này thì khi submit thì form sẽ chuyển dữ liệu về controller và action đấy.

Ví dụ:
//ta tạo ra một form trong action có tên là add
<?php echo $form->create('Recipe'); ?>
//Dữ liệu trả về html:
<form id="RecipeAddForm" method="post" action="/recipes/add">

Các tham số truyền vào:
$model: tên model dùng để khởi tạo form đấy.
$option: Các thuộc tính khai báo thêm cho form đấy bao gồm
+ $options['type']: Chỉ định các phương thức truyền dữ liệu. Giá trị hợp lệ bao gồm ‘post’, ‘get’, ‘file’, ‘put’ và ‘delete’.

Ví dụ:
<?php echo $form->create('User', array('type' => 'get')); ?>
//Dữ liệu trả về html
<form id="UserAddForm" method="get" action="/users/add">

<?php echo $form->create('User', array('type' => 'file')); ?>
//Dữ liệu trả về html
<form id="UserAddForm" enctype="multipart/form-data" method="post" action="/users/add">

+options['url']: Chỉ định đường dẫn khi form truyền dữ liệu. Giá trị url có thể truyền vào một chuỗi hay một mảng.

Ví dụ:
<?php echo $form->create(null, array('url' => '/recipes/add')); ?>
// hoặc
<?php echo $form->create(null, array('url' => array('controller' => 'recipes', 'action' => 'add'))); ?>
//Dữ liệu trả về html:
<form method="post" action="/recipes/add">

<?php echo $form->create(null, array('url' => 'http://www.google.com/search', 'type' => 'get')); ?>
//Dữ liệu trả về html:
<form method="get" action="http://www.google.com/search">

+options['action']:  Cho phép chỉ định một action bất kỳ trong controller hiện tại. Giả sử bạn muốn truyền dữ liệu tới form login trong controller hiện tại, bạn có thể khai báo như sau:

<?php echo $form->create('User', array('action' => 'login')); ?>
//Dữ liệu trả về html:
<form id="UserLoginForm" method="post" action="/users/login">
</form>
7. form->end: tạo ra một thẻ form đóng
Cú pháp:

$form->end(’submitName’);

Tạo ra một thẻ form đóng trong trường hợp đã sử dụng $form->create.

Ví dụ:
<?php echo $form->create(); ?>

<!-- Form elements go here -->

<?php echo $form->end(); ?>
hoặc:
<?php echo $form->end('Finish'); ?>

//Dữ liệu trả về html

<div class="submit">
<input type="submit" value="Finish" />
</div>
</form>

Cakephp 1.2 final ra lò

December 29th, 2008 by ngocbd

Cakephp 1.2 final ra lò

Today, the history of the CakePHP grows stronger. December 25, 2008 will be remembered as one of the most important points in this history. After exactly 2 yrs from the first development release, we can happily say we have the most stable and powerful web framework available. Please enjoy our big present to you, CakePHP 1.2 stable [1]. For this release, we have removed the test files from the build, and created a tag in SVN.

Through the last two years, we have been blessed by a dedicated, talented, and opinionated community[2]. We have shared disagreements[3] and triumphs. We have won popularity contests[4] and been hated on. We have seen CakePHP grow into a truly international community[5]. All of these events have generated an immense amount of passion for CakePHP.

No one is more passionate about CakePHP than the developers[6] who close tickets and fix bugs. We started out two years ago with a small team that dedicated countless hours to implementing new features into 1.2 and maintaining 1.1 stable. This team ensured the integrity of code and vision of the project. When we needed to grow, we found members of the community who showed the same amount of dedication and passion for CakePHP. And with the launch of CakeBOOK, on http://book.cakephp.org, we have seen the dedication and passion further extend to all the contributors and translators[7] of the fantastic documentation that makes learning about the power of CakePHP a bit easier.

We have seen CakePHP adopted by large projects[8] and the growth of dedicated service companies[9]. We have held a workshop[10] to spread the knowledge and passion of CakePHP. And ultimately, we implemented a huge list of features…

  • - Tests!
    • - All classes are test-covered, with good code coverage
    • - Test suite now integrated into the framework
    • - test generation
    • - support for coverage analysis
  • - Command-line infrastructure
    • - with more shell scripts and ability to write custom ones easily
  • - Plugin architecture
    • - Plugins are now distributable as packaged collections of files
    • - Can be loaded from your main app with a dot syntax
  • - Internationalization and Localization support
    • - i18n and l10n classes
    • - Support for unicode strings
  • - Auth component
    • - automatically handles sessions for authenticated users
    • - ties into ACL for automatic denial of protected content or actions
  • - Email component
    • - for generation of text and html email
  • - Security component
    • - HTTP auth support, great for web services
    • - CSRF protection
  • - Cookie component
    • - for secure cookie handling
  • - Custom model finders
    • - simplified syntax
  • - powerful and extensible
  • - Join models
    • - for modeling and accessing HABTM join tables
  • - Behaviors, new way to extend models
    • - Supports “mixing in” new functionality
  • - Containable behavior
    • - simplified query optimization
  • - Validation system extended
    • - with new Validation class, lots of rules
  • - multiple rules and messages
  • - Database drivers
    • - support for many more databases including DB2 and Oracle
  • - Caching
    • - Adapter-driven caching, with support for APC/XCache/Memcache
  • - Set class,
    • - for magical array hacking
  • - Socket and HttpSocket classes
    • - for dealing with remote data and services
  • - Debugger class, for detailed introspection of errors
    • - Get stack traces anywhere in your code
    • - Introspected help on errors, with context information
  • - Pagination
    • - one of the first additions to the new version
    • - one of the simplest systems known
  • - Proper Routing
    • - mapResources() method for exposing controllers via REST
    • - Reverse routing support
    • - Named arguments
    • - Magic variables for common regexes
    • - Support for file extensions with custom content type mappings
  • - View stuff
    • - Separate templates for different content types
    • - automatic switching with RequestHandler
    • - New helper callbacks
    • - renderElement() replaced with element(), added built-in caching support
  • - FormHelper
    • - All form-related methods moved here
    • - New dot notation
    • - Support for associations and multiple records
    • - Huge automation and introspection support; form creation requires very little code
  • - Configure and App classes
    • - for configuration and loading
  • - Replaces defines and global functions

We hope that was a fun read. The changes since 1.1 have been dramatic, but to us this was the minimum set of features needed to a truly powerful framework and realize our vision for maintainability, flexibility, and extensibility.

Almost as dramatic as the feature set, was the growth of the community over this time, especially with its adoption of testing. We are proud of the fact that Cake is one of the most test covered frameworks. Test coverage allows us to fix more bugs and produce the most stable framework available. We believe that a feature is not truly a feature if there is even one known bug. With that in mind, each release comes with the expectation that no bugs are known at the time.

Many of you may remember the first release of 1.2. Back on Dec 25, 2006 we released at revision 4206. Many features had not been implemented or finalized, but we had a taste of what was to come. With this release at [7958], we have come a long way. But possibly the most exciting aspect of being where we are on Dec 25, 2008, is what we expect to see in the future.

CakePHP helps build amazingly powerful applications. We have a running list of examples[11]. Many of these applications were built with earlier versions of 1.2. With the release of CakePHP 1.2 stable, we expect these applications to enjoy a long history, just like the CakePHP project itself.

If you have made it this far, we would like to pass on a few extra goodies we have been working on. First is the all new Cake 1.2 cheatsheet. The old CakeSheet has proved to be a simple, quick reference to some of the power of CakePHP. This new version is the start of several more to come. Second, the gorgeous DebugKit plugin. This plugin helps you develop your application faster by providing quick, easy access to a lot of valuable debugging information. DebugKit also provides and excellent example of how you can build plugins to extend the functionality of you application. Finally, for all the TextMate users out there we have an updated CakePHP TextMate bundle. Joel Perras has put in a great amount of work and coding CakePHP in TextMate just got a lot easier thanks to him. For all these great resources and more, head on over to the downloads[12] page.

We hope you enjoy the big present and the few goodies. Have a great holiday season.
- Gwoo, Nate, PhpNut and the rest of the CakePHP team

download bản final ở đây

Sử dụng Helper TinyMCE trong Cakephp 1.2

November 30th, 2008 by hoanbn

Sử dụng tinyMCE trong cakephp đã được chaubl hướng dẫn ở bài trước (http://i-php.net/2008/10/cakephp-tinymce-ibrowser/). Tuy nhiên ở đây tôi sẽ hướng dẫn các bạn sử dụng TinyMCE thông qua một helper TinyMCE của cakephp.

Cài đặt TinyMCE

Bạn có thể download bản tinymce mới nhất tại địa chỉ http://tinymce.moxiecode.com/download.php và copy thư mục /tinymce/jscripts/tiny_mce vào thư mục /app/webroot/js.

Tạo ra helper TinyMCE

Bạn tạo một helper tinymce theo đường dẫn : app/views/helpers/tinymce.php . Bạn vào  http://i-php.net/2008/11/helper-tinymce/ để lấy source nhé.

Sử dụng trong controller

Bạn khai báo sử dụng helper tinymce trong controller như sau:

var $helpers = Array('Form', 'Tinymce'); 
Sử dụng trong view

Sử dụng tinymce hepler trong view sẽ tương tự như sử dụng các hepler form, html trong cakephp. Để khai báo một ô textarea sử dụng tinymce bạn chỉ việc thêm đoạn code sau vào:

<?php echo $tinymce->input('content') ?>

Sau đây là 2 trang view code mẫu để các bạn tham khảo:

đoạn code 1:

<div class="form-container">
  <?php echo $form->create('Page'); ?>
    <fieldset>
      <legend>Page</legend>
      <?php
        echo $form->input('title');
        echo $tinymce->input('content');
      ?>
    </fieldset>
  <?php echo $form->end('Save'); ?>
</div>

đoạn code 2: ở đây sẽ cấu hình một vài option của tinyMCE

<div class="form-container">
  <?php echo $form->create('Page'); ?>
    <fieldset>
      <legend>Page</legend>
      <?php
        echo $form->input('title');
        echo $tinymce->input('content', null, array(
          'theme'                             => 'advanced',
          'theme_advanced_toolbar_location'   => 'top',
          'theme_advanced_toolbar_align'      => 'left',
          'theme_advanced_statusbar_location' => 'bottom',
        ));
      ?>
    </fieldset>
  <?php echo $form->end('Save'); ?>
</div>

Sự tiện ích khi sử dụng helper TinyMCE này là các bạn có thể tuỳ ý chọn ô textarea nào sử dụng tinyMCE cũng được, ta có thể tuỳ ý cấu hình từng ô nhập textarea cho phù hợp với ý đồ của mình. Good luck.

Helper TinyMCE

November 30th, 2008 by hoanbn

Bạn có thể tham khảo hướng dẫn sử dụng tại: http://i-php.net/2008/11/sử-dụng-helper-tinymce-trong-cakephp-12/

Tạo file app/views/helpers/tinymce.php.

<?php
class TinyMceHelper extends AppHelper
{

    // Take advantage of other helpers
    var $helpers = array('Javascript', 'Form');
    // Check if the tiny_mce.js file has been added or not
    var $_script = false;

    /**
     * Adds the tiny_mce.js file and constructs the options
     *
     * @param string $fieldName Name of a field, like this "Modelname.fieldname", "Modelname/fieldname" is deprecated
     * @param array $tinyoptions Array of TinyMCE attributes for this textarea
     * @return string JavaScript code to initialise the TinyMCE area
     */
    function _build($fieldName, $tinyoptions = array())
    {
        if(!$this->_script)
        {
            // We don't want to add this every time, it's only needed once
            $this->_script = true;
            $this->Javascript->link('tiny_mce/tiny_mce.js', false);
        }
        // Ties the options to the field
        $tinyoptions['mode'] = 'exact';
        $tinyoptions['elements'] = $this->domId($fieldName);
        return $this->Javascript->codeBlock('tinyMCE.init(' . $this->Javascript->object($tinyoptions) . ');');
    }

    /**
     * Creates a TinyMCE textarea.
     *
     * @param string $fieldName Name of a field, like this "Modelname.fieldname", "Modelname/fieldname" is deprecated
     * @param array $options Array of HTML attributes.
     * @param array $tinyoptions Array of TinyMCE attributes for this textarea
     * @return string An HTML textarea element with TinyMCE
     */
    function textarea($fieldName, $options = array(), $tinyoptions = array(), $preset = null)
    {
        // If a preset is defined
        if(!empty($preset))
        {
            $preset_options = $this->preset($preset);

            // If $preset_options && $tinyoptions are an array
            if(is_array($preset_options) && is_array($tinyoptions))
            {
                $tinyoptions = array_merge($preset_options, $tinyoptions);
            }
            else
            {
                $tinyoptions = $preset_options;
            }
        }

        return $this->Form->textarea($fieldName, $options) . $this->_build($fieldName, $tinyoptions);
    }

    /**
     * Creates a TinyMCE textarea.
     *
     * @param string $fieldName Name of a field, like this "Modelname.fieldname", "Modelname/fieldname" is deprecated
     * @param array $options Array of HTML attributes.
     * @param array $tinyoptions Array of TinyMCE attributes for this textarea
     * @return string An HTML textarea element with TinyMCE
     */
    function input($fieldName, $options = array(), $tinyoptions = array(), $preset = null)
    {
        // If a preset is defined
        if(!empty($preset))
        {
            $preset_options = $this->preset($preset);

            // If $preset_options && $tinyoptions are an array
            if(is_array($preset_options) && is_array($tinyoptions))
            {
                $tinyoptions = array_merge($preset_options, $tinyoptions);
            }
            else
            {
                $tinyoptions = $preset_options;
            }
        }

        $options['type'] = 'textarea';
        return $this->Form->input($fieldName, $options) . $this->_build($fieldName, $tinyoptions);
    }

    /**
     * Creates a preset for TinyOptions
     *
     * @param string $name
     * @return array
     */
    private function preset($name)
    {
        // Full Feature
        if($name == 'full')
        {
            return array(
                'theme' => 'advanced',
                'plugins' => 'safari,pagebreak,style,layer,table,save,advhr,advimage,advlink,emotions,iespell,inlinepopups,insertdatetime,preview,media,searchreplace,print,contextmenu,paste,directionality,fullscreen,noneditable,visualchars,nonbreaking,xhtmlxtras,template',
                'theme_advanced_buttons1' => 'save,newdocument,|,bold,italic,underline,strikethrough,|,justifyleft,justifycenter,justifyright,justifyfull,styleselect,formatselect,fontselect,fontsizeselect',
                'theme_advanced_buttons2' => 'cut,copy,paste,pastetext,pasteword,|,search,replace,|,bullist,numlist,|,outdent,indent,blockquote,|,undo,redo,|,link,unlink,anchor,image,cleanup,help,code,|,insertdate,inserttime,preview,|,forecolor,backcolor',
                'theme_advanced_buttons3' => 'tablecontrols,|,hr,removeformat,visualaid,|,sub,sup,|,charmap,emotions,iespell,media,advhr,|,print,|,ltr,rtl,|,fullscreen',
                'theme_advanced_buttons4' => 'insertlayer,moveforward,movebackward,absolute,|,styleprops,|,cite,abbr,acronym,del,ins,attribs,|,visualchars,nonbreaking,template,pagebreak',
                'theme_advanced_toolbar_location' => 'top',
                'theme_advanced_toolbar_align' => 'left',
                'theme_advanced_statusbar_location' => 'bottom',
                'theme_advanced_resizing' => true,
                'theme_advanced_resize_horizontal' => false,
                'convert_fonts_to_spans' => true
            );
        }

        // Basic
        if($name == 'basic')
        {
            return array(
                'theme' => 'advanced',
                'theme_advanced_toolbar_location' => 'top',
                'theme_advanced_toolbar_align' => 'left',
                'theme_advanced_statusbar_location' => 'bottom',
                'theme_advanced_resizing' => true,
                'theme_advanced_resize_horizontal' => false,
                'convert_fonts_to_spans' => true
            );
        }

        // BBCode
        if($name == 'bbcode')
        {
            return array(
                'theme' => 'advanced',
                'plugins' => 'bbcode',
                'theme_advanced_buttons1' => 'bold,italic,underline,undo,redo,link,unlink,image,forecolor,styleselect,removeformat,cleanup,code',
                'theme_advanced_buttons2' => '',
                'theme_advanced_buttons3' => '',
                'theme_advanced_toolbar_location' => 'top',
                'theme_advanced_toolbar_align' => 'left',
                'theme_advanced_styles' => 'Code=codeStyle;Quote=quoteStyle',
                'theme_advanced_statusbar_location' => 'bottom',
                'theme_advanced_resizing' => true,
                'theme_advanced_resize_horizontal' => false,
                'entity_encoding' => 'raw',
                'add_unload_trigger' => false,
                'remove_linebreaks' => false,
                'inline_styles' => false
            );
        }

        return null;
    }
}
?>

Sử dụng Element trong Cakephp

November 28th, 2008 by hoanbn

Element thật sự là cần thiết khi chúng ta muốn sử dụng một đoạn code nhiều lần trong view hoặc layout. Thay vì chúng ta viết đi viết lại nhiều lần trong các view với một đoạn source giống nhau thì chúng ta chỉ việc viết một lần trong element và sử dụng chúng nhiều lần. Việc tạo một element sử dụng nhiều lần trong cakephp sẽ rất dễ dàng khi chúng ta sử dụng hàm requestAction. Sau đây tôi sẽ hướng dẫn các bạn sử dụng element mà dùng được trong cả cakephp 1.1 lẫn cakephp 1.2.

Đầu tiên chúng ta sẽ tạo ra controller Post như sau:

<?php
class PostsController extends AppController {
var
$name = 'Posts';

function index() {
$posts = $this->Post->findAll();

//Kiểm tra xem hàm requestAction có được gọi hay không
if(isset(
$this->params['requested'])) {
return
$posts;
}
$this->set('posts', $posts);
}
}
?>

Trong hàm index trên ta sẽ kiểm tra xem nó có được gọi bằng hàm requestAciton hay không. Nếu có thì hàm sẽ trả về một mảng $posts. Bây giờ chúng ta sẽ tạo ra một element post.ctp (hay post.thml trong cakephp 1.1) có đường dẫn như sau: /app/elements/posts.ctp.

<?php

$posts = $this->requestAction('posts/index');
foreach($posts as $post):
echo $post['Post']['title'];
endforeach;

?>

Để sử dụng element trên, chúng ta chỉ việc thêm đoạn code sau vào các view hoặc layout là xong.

<?php echo $this->renderElement('posts');?>

Vậy là xong.

« Previous Entries