21 Aug 2009 @ 2:56 AM 








sometime we need export data to excel file. i have simple helper for write data to xls file . this script writing By Cleiton Wasen (wasenbr).

1. create file xls.php to  app/views/helpers/xls.php


2. create view templates file app/views/…/xls.thtml

setHeader('text_'.date('Y_m_d').'.xls');
// XLS Data Cell
$xls->BOF();
$xls->writeLabel(1,0,"Student Register");
$xls->writeLabel(2,0,"COURSENO : ");
$xls->writeLabel(2,1,"123");
$xls->writeLabel(3,0,"TITLE : ");
$xls->writeLabel(3,0,"BlaBlaBla");
$xls->writeLabel(4,0,"SETION : ");
$xls->writeLabel(6,0,"NO");
$xls->writeLabel(6,1,"ID");
$xls->writeLabel(6,2,"Gender");
$xls->writeLabel(6,3,"Name");
$xls->writeLabel(6,4,"Lastname");
$xls->writeLabel(7,0,"NO");
$xls->writeLabel(7,1,"ID");
$xls->writeLabel(7,2,"Gender");
$xls->writeLabel(7,3,"Name");
$xls->writeLabel(7,4,"Lastname");
$xls->EOF();

exit();
?>


Tags Tags: , , ,
Categories: CakePHP
Posted By: asbin
Last Edit: 10 Jun 2010 @ 12 17 AM

EmailPermalinkComments (2)








if you need thumnail the image, display on your page. you can use helper image thumbnail. this is helpers code for that :

1. you must copy this code on directory app/views/helpers/image.php:

<?php
class ImageHelper extends Helper {

var $helpers = array(‘Html’);

var $cacheDir = ‘imagecache’; // relative to IMAGES_URL path

/**
* Automatically resizes an image and returns formatted IMG tag
*
* @param string $path Path to the image file, relative to the webroot/img/ directory.
* @param integer $width Image of returned image
* @param integer $height Height of returned image
* @param boolean $aspect Maintain aspect ratio (default: true)
* @param array    $htmlAttributes Array of HTML attributes.
* @param boolean $return Wheter this method should return a value or output it. This overrides AUTO_OUTPUT.
* @return mixed    Either string or echos the value, depends on AUTO_OUTPUT and $return.
* @access public
*/
function resize($path, $width, $height, $aspect = true, $htmlAttributes = array(), $return = false) {

$types = array(1 => “gif”, “jpeg”, “png”, “swf”, “psd”, “wbmp”); // used to determine image type

$fullpath = ROOT.DS.APP_DIR.DS.WEBROOT_DIR.DS.$this->themeWeb.IMAGES_URL;

$url = $fullpath.$path;

if (!($size = getimagesize($url)))
return; // image doesn’t exist

if ($aspect) { // adjust to aspect.
if (($size[1]/$height) > ($size[0]/$width))  // $size[0]:width, [1]:height, [2]:type
$width = ceil(($size[0]/$size[1]) * $height);
else
$height = ceil($width / ($size[0]/$size[1]));
}

$relfile = $this->webroot.$this->themeWeb.IMAGES_URL.$this->cacheDir.’/’.$width.’x’.$height.’_’.basename($path); // relative file
$cachefile = $fullpath.$this->cacheDir.DS.$width.’x’.$height.’_’.basename($path);  // location on server

if (file_exists($cachefile)) {
$csize = getimagesize($cachefile);
$cached = ($csize[0] == $width && $csize[1] == $height); // image is cached
if (@filemtime($cachefile) < @filemtime($url)) // check if up to date
$cached = false;
} else {
$cached = false;
}

if (!$cached) {
$resize = ($size[0] > $width || $size[1] > $height) || ($size[0] < $width || $size[1] < $height);
} else {
$resize = false;
}

if ($resize) {
$image = call_user_func(‘imagecreatefrom’.$types[$size[2]], $url);
if (function_exists(“imagecreatetruecolor”) && ($temp = imagecreatetruecolor ($width, $height))) {
imagecopyresampled ($temp, $image, 0, 0, 0, 0, $width, $height, $size[0], $size[1]);
} else {
$temp = imagecreate ($width, $height);
imagecopyresized ($temp, $image, 0, 0, 0, 0, $width, $height, $size[0], $size[1]);
}
call_user_func(“image”.$types[$size[2]], $temp, $cachefile);
imagedestroy ($image);
imagedestroy ($temp);
}

return $this->output(sprintf($this->Html->tags['image'], $relfile, $this->Html->parseHtmlOptions($htmlAttributes, null, ”, ‘ ‘)), $return);
}
}
?>

2. you need call image class on your controller. if you can use the helper

this is code on your controller:

<?php
class PagesController extends AppController{

var $name = ‘Pages’;
var $helpers = array(‘Html’, ‘Javascript’,'Ajax’,'image’);

function index(){
}
function image(){

}

}

?>

that code example use the pages controller.

3. you must call that helpers. place this code on app/views/pages/image.thtml for call the image helpers and copy example image to app/webroot/img/myimage.jpg , create directory app/webroot/img/imagecache for save the image thumbnail.

to call the helpers use this code on your view:

<?
echo $image->resize(‘myimage.jpg’, 150, 150, true);
?>

ok, that code can be use on yor program. good luck to try.

Tags Tags: , , , , ,
Categories: CakePHP
Posted By: asbin
Last Edit: 29 Jul 2009 @ 06 10 AM

EmailPermalinkComments (0)
 26 Jul 2009 @ 11:14 PM 

CAPTCHA

captcha is generating library for generating visual (completely automated public Turing test to tell computers and humans apart).

captcha can generate useing component on cake php:

Component Class:

<?php

vendor(‘CaptchaSecurityImages’);

class CaptchaComponent extends Object
{

var $controller;
var $captcha;

function startup(&$controller) {
$this->controller = $controller;
}

function initialize($width = 60, $height = 22, $char = 6, $sec_code = ”)
{
$this->captcha = new CaptchaSecurityImages($width, $height, $char, $sec_code);
}

function code()
{
return $this->captcha->getCode();
}

function secCode()
{
return $this->captcha->getSecCode();
}

function render() {
$this->captcha->render();
return true;
}

function check($userCode, $secCode = ”)
{
if(empty($secCode)){
if($userCode == $_SESSION['security_code']){
unset($_SESSION['security_code']);
return true;
}
}else{
if($userCode == $_SESSION['custom_security_code'][$secCode]){
unset($_SESSION['custom_security_code'][$secCode]);
return true;
}
}
return false;
}

}
?>


Use it in your controller:
<?php
class KomentarsController extends AppController{

var $name = ‘Komentars’;
var $components = array(‘Captcha’);
var $helpers = array(‘Html’,'Ajax’, ‘Javascript’);
function index(){
//echo $_SESSION['security_code'];
//echo @$_SESSION['custom_security_code'][$secCode];

if(!$this->Captcha->check($this->data['Komentar']['code'])){
$pc = ”
<script type=\”text/javascript\”>
Modalbox.show(‘&lt;span&gt;Wrong security code.&lt;/span&gt;’, {title: ‘Status’, width: 300});
</script>
“;
$this->set(‘alert’,'Kode verifikasi salah atau belum di isi’);
$alert=”Kode verifikasi salah atau belum di isi”;
//$_SESSION['popupconfirm'] = $pc;
// $this->redirect(‘/request-a-quote’);
//exit;

}else{

}

}

function captcha_image(){
$this->Captcha->initialize();
$this->Captcha->render();
}

}
?>

Display captcha image, in your template view:

<img id=”finder_form_captcha”  src=”<?php echo $html->url(‘/komentars/captcha_image’);?>” alt=”" />
place vendors class on vendor directory:

<?php

/*
* File: CaptchaSecurityImages.php
* Author: Simon Jarvis
* Copyright: 2006 Simon Jarvis
* Date: 03/08/06
* Updated: 07/02/07
* Requirements: PHP 4/5 with GD and FreeType libraries
* Link: http://www.white-hat-web-design.co.uk/articles/php-captcha.php
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details:
* http://www.gnu.org/licenses/gpl.html
*
*/

class CaptchaSecurityImages {

var $font = ‘monofont.ttf’;
var $code = ”;
var $width = 0;
var $height = 0;
var $characters = 0;
var $sec_code = ”;

function __construct($width = ’120′, $height = ’40′, $characters = ’6′,$sec_code=”) {
$this->code = $this->generateCode($characters);
$this->width = $width;
$this->height = $height;
$this->characters = $characters;
$this->sec_code = $sec_code;
$this->font = APP . ‘vendors/monofont.ttf’;
//$this->font = BASE_DIR . ‘vendors/monofont.ttf’;
//$this->font = ‘monofont.ttf’;

if(empty($this->sec_code)){
$_SESSION['security_code'] = $this->code;
}else{
$_SESSION['custom_security_code'][$this->sec_code] = $this->code;
}
}

/*$_SESSION['custom_security_code']['company'] = ‘DDRTYU’;
$_SESSION['custom_security_code']['blog'] = ‘ADDASU’;
$_SESSION['custom_security_code']['press'] = ‘ASDSAD’;*/

function getCode()
{
return $this->code;
}

function getSecCode()
{
return $this->sec_code;
}

function render()
{
/* font size will be 75% of the image height */
$font_size = $this->height * 0.75;
$image = @imagecreate($this->width, $this->height) or die(‘Cannot initialize new GD image stream’);

/* set the colours */
$background_color = imagecolorallocate($image, 255, 255, 255);
$line_color = imagecolorallocate($image, 0, 0, 0);
$text_color = imagecolorallocate($image, 0, 0, 0);
$noise_color = imagecolorallocate($image, 100, 120, 180);

/* create textbox and add text */
$textbox = imagettfbbox($font_size, 0, $this->font, $this->code) or die(‘Error in imagettfbbox function’);
$x = ($this->width – $textbox[4])/2;
$y = ($this->height – $textbox[5])/2;
imagettftext($image, $font_size, 5, $x, $y, $text_color, $this->font , $this->code) or die(‘Error in imagettftext function’);
imagerectangle($image, 0, 0, $this->width-1, $this->height-1, $line_color);

/* output captcha image to browser */
header(‘Content-Type: image/jpeg’);
imagejpeg($image);
imagedestroy($image);
}

function generateCode($characters)
{
/* list all possible characters, similar looking characters and vowels have been removed */
$possible = ’23456789bcdfghjkmnpqrstvwxyz’;
$code = ”;
$i = 0;
while ($i < $characters) {
$code .= substr($possible, mt_rand(0, strlen($possible)-1), 1);
$i++;
}

return $code;
}

}
?>

Tags Categories: CakePHP Posted By: asbin
Last Edit: 26 Jul 2009 @ 11 17 PM

EmailPermalinkComments (1)
 26 Jun 2009 @ 4:01 AM 

many posts on the web page or blog. cause the page too long.  because of that, content on the web need pagination.follow the tutorial for creating pagination:

on cake php pagination created with class component and class element.

Component:

place component on directotry /app/controller/component/pagination.php

Element:

place component on directotry /app/views/elements/pagination.thtml

helpers :

place component on directotry /app/views/helpers/pagination.php

if that file placed on the each directory. that class must be call from controller . this is a example call the class pagination on controller :

<?php

class PagesController extends AppController {

var $uses = array(‘Data’);
var $helpers = array(‘Html’,'Pagination’,'Javascript’,'Ajax’);
var $components = array(‘Paginations’);
var $paging;

$criteria=”";
list($order,$limit,$page) = $this->Paginations->init($criteria);
$result=$this->Data->findAll(null,null,null,$limit,$page);

$this->set(‘data’,$result);

?>

to download full code and real example, you can download script on this link DOWNLOAD

Tags Tags: , , , , , , , ,
Categories: CakePHP
Posted By: asbin
Last Edit: 26 Jun 2009 @ 04 01 AM

EmailPermalinkComments (0)
 04 Jun 2009 @ 12:58 AM 

multiple uplaod file dengan cakephp

multi file upload dengan cakephp. multi upload digunakan untuk meng upload beberapa file secara bersamaan.  untuk download script silahkan klik di sini untuk DOWNLOAD

Tags Tags:
Categories: CakePHP
Posted By: asbin
Last Edit: 04 Jun 2009 @ 12 58 AM

EmailPermalinkComments (0)
 31 May 2009 @ 10:24 AM 

Aksi tambah, ubah, ambil dan hapus data adalah aksi yang paling sering digunakan dalam aplikasi database, termasuk website dinamis seperti halnya web CMS. nah kali ini akan saya bahas tentang ke empat aksi tersebut dalam cake php

sebelumnya telah di bahas tentang model dan controller. script perintah add,edit,Retrieving,delete data dituliskan dalam controller sedangakan penggunaan tabelnya akan ditentukan oleh MODEL. sehingga untuk mengakses tabel model harus di panggil terlebih dahulu sebelum ke empat aksi tersebut di eksekusi.berikt penjelasan selengkapnya..

// menambah,mengedit,mengambil, menghapus data data
kita seringkali menambahkan data ke dalam databese dengan code dasar dari php yaitu “mysql_query(“Query SQL”);“. dalam cake php kita tidak perlu menulisakan query sql karena query secara otomatis di olah oleh engine cake php. disini saya akan mencoba memberikan contoh script menginsertkan data dengan cake php.

pertama, load model yang akan kita gunakan. dalam contoh saya menggunakan model User

<?
class UsersController extends AppController {

var $helpers = array(‘Html’, ‘Javascript’, ‘Ajax’);
var $components = array(‘RequestHandler’,'Security’);

function adduser(){

//memanggil class model User
loadModel(‘User’);
$user=& new User();

//menginsert data ke tabel
$user->save($this->data['User']);

}

function edituser($id){
//memanggil class model User
loadModel(‘User’);
$user=& new User();

//mengubah data
$this->data['User']['id']=$id;
$user->save($this->data['User']);
}
function ambiluser(){
//memanggil class model User
loadModel(‘User’);
$user=& new User();
//mengambil data
$user->findAll();
}

function deluser($id){
//memanggil class model User
loadModel(‘User’);
$user=& new User();

//menghapus data
$user->del($id);
}

}
?>

contoh diatas adalah controller dengan fungsi tambah, ubah, ambil, hapus. nah sekarang akan saya jelaskan satu persatu.

loadModel(‘User’);
$user=& new User();

adalah code untuk memanggil model yang kita gunakan. dalam contoh menggunakan model User. ingat code sase sensitive. class model User di panggil dan di simpan ke variabel $user.

$user->save($this->data['User']);

adalah code untuk menginsertkan data ke dalam tabel. $this->data['User'] adalah variabel yang berisi array data yang dimasukkan ke tabel. code tersebut secara otomatis akan memasukkan data. kamu tidak perlu memasukkan query.

$this->data['User']['id']=$id;
$user->save($this->data['User']);

adalah code untuk mengubah data. sebenarnya code sama dengan code tambah data, cuma variabel yang berisi id harus dideklarasikan terlebih dahulu untuk menentukan data yang di edit.

$user->findAll();
adalah code untuk mengambil semua data dari database. didalam method findAll(). Sebenarnya dalam method ini ada parameter yang bisa digunakan :

findAll( $conditions,
$fields,
$order,
$limit,
$page,
$recursive);

string $conditions;
array $fields;
string $order;
int $limit;
int $page;
int $recursive;

parameter2 menentukan kondisi hasil query yang kita ambil. $recursive untuk membatasi array yang dihasilkan berdasarkan relasi model.

findAllBy( $value);
string $value;

ini digunakan untuk mengambil data berdsarkan field yang dimaksud.

findCount($value);

digunakan untuk mengmbil jumlah record berdasar parameternya.

$user->del($id);

digunakan untuk menghapus record berdasar parameter $id.

demikian sedikit sharingKU TENTANG SCRIPT tambah, ubah , hapus, ambil data dengan cake php. untuk lebih jelas bisa di pelajari pada manual cake . DOWNLOAD DI SINI
terima kasih…………

Tags Tags:
Categories: CakePHP
Posted By: asbin
Last Edit: 31 May 2009 @ 11 00 AM

EmailPermalinkComments (0)
 31 May 2009 @ 9:13 AM 

A model is generally an access point to the database, and more specifically, to a certain table in the database. By default, each model uses the table who’s name is plural of its own, i.e. a ‘User’ model uses the ‘users’ table. Models can also contain data validation rules, association information, and methods specific to the table it uses. Here’s what a simple User model might look like in Cake:

Example 6.1. Example User Model, saved in /app/models/user.php

//AppModel gives you all of Cake's Model functionality

class User extends AppModel
{
// Its always good practice to include this variable.
var $name = 'User';

// This is used for validation, see Chapter "Data Validation".
var $validate = array();

// You can also define associations.
// See section 6.3 for more information.

var $hasMany = array('Image' =>
array(‘className’ => ‘Image’)
);

// You can also include your own functions:
function makeInactive($uid)
{
//Put your own logic here…
}
}

?>
========
resource : manual_cakephp
========

Tags Tags:
Categories: CakePHP
Posted By: asbin
Last Edit: 31 May 2009 @ 09 13 AM

EmailPermalinkComments (2)
 29 May 2009 @ 4:50 AM 

Kali ini saya akan sedikit membahas tentang controller.

Download engine cakephp

Controller digunakan untuk mengatur logika tertentu bagian dari aplikasi kamu. pada directory /app terdapat class appController yang berada dalam file app_controller.php, semua file controller yang kamu buat akan mengacu pada
app_controller.php. sehingga setiap eksekusi yang terjadi akan selalu menjalankan class app_controller.php terlebih dahulu. brikut contoh script Controllernya :


<?

class VideosController extends AppController

var $uses = array(‘Vidio’);
var $helpers = array(‘Html’, ‘Javascript’, ‘Ajax’);
var $components = array(‘RequestHandler’,'Security’);

function beforeFilter(){

}
{

function view($id)
{

$data=”ini data yang akan dikirim ke view view.thtml”;

$this->set(‘data’,$data);

$this->render(‘tampil’);

//aksi algoritma kamu di sini…
}

function edit($customer_id, $video_id)
{
//aksi algoritma kamu di sini…
}

function cari($query)
{
//aksi algoritma kamu di sini…
}


function afterFilter(){

}

function beforeRender(){


}

?>

Script diatas adalah controller dengan dengan class Vidio yang mengacu pada class  app_controller. sedangkan

var $uses = array(‘Vidio’);   adalah deklarasi variable  yang akan memanggil class model dengan nama Vidio pada  model Vidio, sehingga controller dapat mengakses data dari database di tablevidios. atau sederhananya berfungsi untuk memanggil class model vidio agar data dari tabel bisa di akses dalam controller.

var $helpers = array(‘Html’, ‘Javascript’, ‘Ajax’); adalah deklarasi variable  yang akan memanggil helper yaitu fungsi2 bawaan cake yang digunakan untuk mengolah method yang akan menampilkan script HTML, Javascript, Ajax.
var $components = array(‘RequestHandler’,'Security’); adalah deklarasi variable  yang akan memanggil class yang berada pada directory component sehingga fungsi2nya dapat digunakan pada controller.

function beforeFilter(){ } adalah method dari class VideosController yang akan selalu diakses pertama kali saat VideosController di exekusi walaupun method ini tidak di panggil.

function afterFilter(){ } adalah method dari class VideosController yang  diakses pertamakali SETELAH mengakses method  walaupun tidak di panggil

function beforeRender(){ } adalah method dari class VideosController yang  diakses pertamakali SETELAH mengakses methode dan sebelum mengakses views,  walaupun tidak di panggil. view adalah file yang akan diakses setelah proses logic pada controller selesai. view berguna sebagai media penampilan data dari hasil logic controller.

//Interaksi dengan view

pada method view telah saya deklarasikan $this->set(‘data’,$data); yang berarti isi dari variable $data dikirim ke view. sedangkan script $this->render(‘tampil’); akan otomatis memanggil view yang dimasukkan sebagai parameter, pada script ini data dari var $data dikirim ke view tampil.

sementara ini dulu tentang controller cakephp…. tetap semangat ……!!!!!

Tags Tags:
Categories: CakePHP
Posted By: asbin
Last Edit: 29 May 2009 @ 05 03 AM

EmailPermalinkComments (0)
 21 May 2009 @ 5:17 AM 

One of the most powerful features of CakePHP is the relational mapping provided by the model. In CakePHP, the links between tables are handled through associations. Associations are the glue between related logical units.

There are four types of associations in CakePHP:

  • hasOne
  • hasMany
  • belongsTo
  • hasAndBelongsToMany

When associations between models have been defined, Cake will automagically fetch models related to the model you are working with. For example, if a Post model is related to an Author model using a hasMany association, making a call to $this->Post->findAll() in a controller will fetch Post records, as well as all the Author records they are related to.

To use the association correctly it is best to follow the CakePHP naming conventions (see Appendix “Cake Conventions”). If you use CakePHP’s naming conventions, you can use scaffolding to visualize your application data, because scaffolding detects and uses the associations between models. Of course you can always customize model associations to work outside of Cake’s naming conventions, but we’ll save those tips for later. For now, let’s just stick to the conventions. The naming conventions that concern us here are the foreign keys, model names, and table names.

Here’s a review of what Cake expects for the names of these different elements: (see Appendix “Cake Conventions” for more information on naming)

  • Foreign Keys: [singular model name]_id. For example, a foreign key in the “authors” table pointing back to the Post a given Author belongs to would be named “post_id”.
  • Table Names: [plural object name]. Since we’d like to store information about blog posts and their authors, the table names are “posts” and “authors”, respectively.
  • Model Names: [CamelCased, singular form of table name]. The model name for the “posts” table is “Post”, and the model name for the “authors” table is “Author”.
note Associations on cake PHP Note
CakePHP’s scaffolding expects your associations to be in the same order as your colums. So if I have an Article that belongsTo three other models (Author, Editor, and Publisher), I would need three keys: author_id, editor_id, and publisher_id. Scaffolding would expect your associations in the same order as the keys in the table (e.g. first Author, second Editor, lastly Publisher).

In order to illustrate how some of these associations work, let’s continue using the blog application as an example. Imagine that we’re going to create a simple user management system for the blog. I suppose it goes without saying we’ll want to keep track of Users, but we’d also like each user to have an associated Profile (User hasOne Profile). Users will also be able to create comments and remain associated to them (User hasMany Comments). Once we have the user system working, we’ll move to allowing Posts to be related to Tag objects using the hasAndBelongsToMany relationship (Post hasAndBelongsToMany Tags).

Defining and Querying with hasOne

In order to set up this association, we’ll assume that you’ve already created the User and Profile models. To define the hasOne assocation between them, we’ll need to add an array to the models to tell Cake how they relate. Here’s how that looks like:

Example 6.5. /app/models/user.php hasOne

<?php
class User extends AppModel
{
    var $name = 'User';
    var $hasOne = array('Profile' =>
                        array('className'    => 'Profile',
                              'conditions'   => '',
                              'order'        => '',
                              'dependent'    =>  true,
                              'foreignKey'   => 'user_id'
                        )
                  );
}
?>


The $hasOne array is what Cake uses to build the association between the User and Profile models. Each key in the array allows you to further configure the association:

  • className (required): the classname of the model you’d like to associateFor our example, we want to specify the ‘Profile’ model class name.
  • conditions: SQL condition fragments that define the relationshipWe could use this to tell Cake to only associate a Profile that has a green header, if we wished. To define conditions like this, you’d specify a SQL conditions fragment as the value for this key: “Profile.header_color = ‘green’”.
  • order: the ordering of the associated modelsIf you’d like your associated models in a specific order, set the value for this key using an SQL order predicate: “Profile.name ASC”, for example.
  • dependent: if set to true, the associated model is destroyed when this one is.For example, if the “Cool Blue” profile is associated to “Bob”, and I delete the user “Bob”, the profile “Cool Blue” will also be deleted.
  • foreignKey: the name of the foreign key that points to the associated model.This is here in case you’re working with a database that doesn’t follow Cake’s naming conventions.

Now, when we execute find() or findAll() calls using the Profile model, we should see our associated User model there as well:

$user = $this->User->read(null, '25');
print_r($user);

//output:

Array
(
    [User] => Array
        (
            [id] => 25
            [first_name] => John
            [last_name] => Anderson
            [username] => psychic
            [password] => c4k3roxx
        )

    [Profile] => Array
        (
            [id] => 4
            [name] => Cool Blue
            [header_color] => aquamarine
            [user_id] = 25
        )
)

Defining and Querying with belongsTo

Now that a User can see its Profile, we’ll need to define an association so Profile can see its User. This is done in Cake using the belongsTo assocation. In the Profile model, we’d do the following:

Example 6.6. /app/models/profile.php belongsTo

<?php
class Profile extends AppModel
{
    var $name = 'Profile';
    var $belongsTo = array('User' =>
                           array('className'  => 'User',
                                 'conditions' => '',
                                 'order'      => '',
                                 'foreignKey' => 'user_id'
                           )
                     );
}
?>


The $belongsTo array is what Cake uses to build the association between the User and Profile models. Each key in the array allows you to further configure the association:

  • className (required): the classname of the model you’d like to associateFor our example, we want to specify the ‘User’ model class name.
  • conditions: SQL condition fragments that define the relationshipWe could use this to tell Cake to only associate a User that is active. You would do this by setting the value of the key to be “User.active = ’1′”, or something similar.
  • order: the ordering of the associated modelsIf you’d like your associated models in a specific order, set the value for this key using an SQL order predicate: “User.last_name ASC”, for example.
  • foreignKey: the name of the foreign key that points to the associated model.This is here in case you’re working with a database that doesn’t follow Cake’s naming conventions.

Now, when we execute find() or findAll() calls using the Profile model, we should see our associated User model there as well:

$profile = $this->Profile->read(null, '4');
print_r($profile);

//output:

Array
(

    [Profile] => Array
        (
            [id] => 4
            [name] => Cool Blue
            [header_color] => aquamarine
            [user_id] = 25
        )

    [User] => Array
        (
            [id] => 25
            [first_name] => John
            [last_name] => Anderson
            [username] => psychic
            [password] => c4k3roxx
        )
)

Defining and Querying with hasMany

Now that User and Profile models are associated and working properly, let’s build our system so that User records are associated to Comment records. This is done in the User model like so:

Example 6.7. /app/models/user.php hasMany

<?php
class User extends AppModel
{
    var $name = 'User';
    var $hasMany = array('Comment' =>
                         array('className'     => 'Comment',
                               'conditions'    => 'Comment.moderated = 1',
                               'order'         => 'Comment.created DESC',
                               'limit'         => '5',
                               'foreignKey'    => 'user_id',
                               'dependent'     => true,
                               'exclusive'     => false,
                               'finderQuery'   => ''
                         )
                  );

    // Here's the hasOne relationship we defined earlier...
    var $hasOne = array('Profile' =>
                        array('className'    => 'Profile',
                              'conditions'   => '',
                              'order'        => '',
                              'dependent'    =>  true,
                              'foreignKey'   => 'user_id'
                        )
                  );
}
?>


The $hasMany array is what Cake uses to build the association between the User and Comment models. Each key in the array allows you to further configure the association:

  • className (required): the classname of the model you’d like to associateFor our example, we want to specify the ‘Comment’ model class name.
  • conditions: SQL condition fragments that define the relationshipWe could use this to tell Cake to only associate a Comment that has been moderated. You would do this by setting the value of the key to be “Comment.moderated = 1″, or something similar.
  • order: the ordering of the associated modelsIf you’d like your associated models in a specific order, set the value for this key using an SQL order predicate: “Comment.created DESC”, for example.
  • limit: the maximum number of associated models you’d like Cake to fetch.For this example, we didn’t want to fetch *all* of the user’s comments, just five.
  • foreignKey: the name of the foreign key that points to the associated model.This is here in case you’re working with a database that doesn’t follow Cake’s naming conventions.
  • dependent: if set to true, the associated model is destroyed when this one is.For example, if the “Cool Blue” profile is associated to “Bob”, and I delete the user “Bob”, the profile “Cool Blue” will also be deleted.
  • exclusive: If set to true, all the associated objects are deleted in one SQL statement without having their beforeDelete callback run.Good for use for simpler associations, because it can be much faster.
  • finderQuery: Specify a complete SQL statement to fetch the association.This is a good way to go for complex associations that depends on multiple tables. If Cake’s automatic assocations aren’t working for you, here’s where you customize it.

Now, when we execute find() or findAll() calls using the User model, we should see our associated Comment models there as well:

$user = $this->User->read(null, '25');
print_r($user);

//output:

Array
(
    [User] => Array
        (
            [id] => 25
            [first_name] => John
            [last_name] => Anderson
            [username] => psychic
            [password] => c4k3roxx
        )

    [Profile] => Array
        (
            [id] => 4
            [name] => Cool Blue
            [header_color] => aquamarine
            [user_id] = 25
        )

    [Comment] => Array
        (
            [0] => Array
                (
                    [id] => 247
                    [user_id] => 25
                    [body] => The hasMany assocation is nice to have.
                )

            [1] => Array
                (
                    [id] => 256
                    [user_id] => 25
                    [body] => The hasMany assocation is really nice to have.
                )

            [2] => Array
                (
                    [id] => 269
                    [user_id] => 25
                    [body] => The hasMany assocation is really, really nice to have.
                )

            [3] => Array
                (
                    [id] => 285
                    [user_id] => 25
                    [body] => The hasMany assocation is extremely nice to have.
                )

            [4] => Array
                (
                    [id] => 286
                    [user_id] => 25
                    [body] => The hasMany assocation is super nice to have.
                )

        )
)
note Associations on cake PHP Note
While we won’t document the process here, it would be a great idea to define the “Comment belongsTo User” association as well, so that both models can see each other. Not defining assocations from both models is often a common gotcha when trying to use scaffolding.

Defining and Querying with hasAndBelongsToMany

Now that you’ve mastered the simpler associations, let’s move to the last assocation: hasAndBelongsToMany (or HABTM). This last one is the hardest to wrap your head around, but it is also one of the most useful. The HABTM association is useful when you have two Models that are linked together with a join table. The join table holds the individual rows that are related to each other.

The difference between hasMany and hasAndBelongsToMany is that with hasMany, the associated model is not shared. If a User hasMany Comments, it is the *only* user associated to those comments. With HABTM, the associated models are shared. This is great for what we’re about to do next: associate Post models to Tag models. When a Tag belongs to a Post, we don’t want it to be ‘used up’, we want to continue to associate it to other Posts as well.

In order to do this, we’ll need to set up the correct tables for this association. Of course you’ll need a “tags” table for you Tag model, and a “posts” table for your posts, but you’ll also need to create a join table for this association. The naming convention for HABTM join tables is [plural model name1]_[plural model name2], where the model names are in alphabetical order:

Example 6.8. HABTM Join Tables: Sample models and their join table names

  • Posts and Tags: posts_tags
  • Monkeys and IceCubes: ice_cubes_monkeys
  • Categories and Articles: articles_categories


HABTM join tables need to at least consist of the two foreign keys of the models they link. For our example, “post_id” and “tag_id” is all we’ll need.

Here’s what the SQL dumps will look like for our Posts HABTM Tags example:

--
-- Table structure for table `posts`
--

CREATE TABLE `posts` (
  `id` int(10) unsigned NOT NULL auto_increment,
  `user_id` int(10) default NULL,
  `title` varchar(50) default NULL,
  `body` text,
  `created` datetime default NULL,
  `modified` datetime default NULL,
  `status` tinyint(1) NOT NULL default '0',
  PRIMARY KEY  (`id`)
) TYPE=MyISAM;

-- --------------------------------------------------------

--
-- Table structure for table `posts_tags`
--

CREATE TABLE `posts_tags` (
  `post_id` int(10) unsigned NOT NULL default '0',
  `tag_id` int(10) unsigned NOT NULL default '0',
  PRIMARY KEY  (`post_id`,`tag_id`)
) TYPE=MyISAM;

-- --------------------------------------------------------

--
-- Table structure for table `tags`
--

CREATE TABLE `tags` (
  `id` int(10) unsigned NOT NULL auto_increment,
  `tag` varchar(100) default NULL,
  PRIMARY KEY  (`id`)
) TYPE=MyISAM;

With our tables set up, let’s define the association in the Post model:

Example 6.9. /app/models/post.php hasAndBelongsToMany

<?php
class Post extends AppModel
{
    var $name = 'Post';
    var $hasAndBelongsToMany = array('Tag' =>
                               array('className'    => 'Tag',
                                     'joinTable'    => 'posts_tags',
                                     'foreignKey'   => 'post_id',
                                     'associationForeignKey'=> 'tag_id',
                                     'conditions'   => '',
                                     'order'        => '',
                                     'limit'        => '',
                                     'unique'       => true,
                                     'finderQuery'  => '',
                                     'deleteQuery'  => '',
                               )
                               );
}
?>


The $hasAndBelongsToMany array is what Cake uses to build the association between the Post and Tag models. Each key in the array allows you to further configure the association:

  • className (required): the classname of the model you’d like to associateFor our example, we want to specify the ‘Tag’ model class name.
  • joinTable: this is here for a database that doesn’t adhere to Cake’s naming conventions. If your table doesn’t look like [plural model1]_[plural model2] in lexical order, you can specify the name of your table here.
  • foreignKey: the name of the foreign key in the join table that points to the current model.This is here in case you’re working with a database that doesn’t follow Cake’s naming conventions.
  • associationForeignKey: the name of the foreign key that points to the associated model.
  • conditions: SQL condition fragments that define the relationshipWe could use this to tell Cake to only associate a Tag that has been approved. You would do this by setting the value of the key to be “Tag.approved = 1″, or something similar.
  • order: the ordering of the associated modelsIf you’d like your associated models in a specific order, set the value for this key using an SQL order predicate: “Tag.tag DESC”, for example.
  • limit: the maximum number of associated models you’d like Cake to fetch.Used to limit the number of associated Tags to be fetched.
  • unique: If set to true, duplicate associated objects will be ignored by accessors and query methods.Basically, if the associations are distinct, set this to true. That way the Tag “Awesomeness” can only be assigned to the Post “Cake Model Associations” once, and will only show up once in result arrays.
  • finderQuery: Specify a complete SQL statement to fetch the association.This is a good way to go for complex associations that depends on multiple tables. If Cake’s automatic assocations aren’t working for you, here’s where you customize it.
  • deleteQuery: A complete SQL statement to be used to remove assocations between HABTM models.If you don’t like the way Cake is performing deletes, or your setup is customized in some way, you can change the way deletion works by supplying your own query here.

Now, when we execute find() or findAll() calls using the Post model, we should see our associated Tag models there as well:

$post = $this->Post->read(null, '2');
print_r($post);

//output:

Array
(
    [Post] => Array
        (
            [id] => 2
            [user_id] => 25
            [title] => Cake Model Associations
            [body] => Time saving, easy, and powerful.
            [created] => 2006-04-15 09:33:24
            [modified] => 2006-04-15 09:33:24
            [status] => 1
        )

    [Tag] => Array
        (
            [0] => Array
                (
                    [id] => 247
                    [tag] => CakePHP
                )

            [1] => Array
                (
                    [id] => 256
                    [tag] => Powerful Software
                )
        )
)

Saving Related Model Data

One important thing to remember when working with associated models is that saving model data should always be done by the corresponding Cake model. If you are saving a new Post and its associated Comments, then you would use both Post and Comment models during the save operation.

If neither of the associated models exists in the system yet (for example, you want to save a new Post and a related Comment at the same time), you’ll need to first save the primary, or parent model. To get an idea of how this works, let’s imagine that we have an action in our PostsController that handles the saving of a new Post and a related Comment. The example action shown below will assume that you’ve posted a single Post and a single Comment.

Example 6.10. /app/controllers/posts_controller.php (partial)

function add()
{
    if (!empty($this->data))
    {
        //We can save the Post data:
        //it should be in $this->data['Post']

        $this->Post->save($this->data);

        //Now, we'll need to save the Comment data
        //But first, we need to know the ID for the
        //Post we just saved...

        $post_id = $this->Post->getLastInsertId();

        //Now we add this information to the save data
        //and save the comment.

        $this->data['Comment']['post_id'] = $post_id;

        //Because our Post hasMany Comments, we can access
        //the Comment model through the Post model:

        $this->Post->Comment->save($this->data);

    }
}


If, however, the parent model already exists in the system (for example, adding a Comment to an existing Post), you need to know the ID of the parent model before saving. You could pass this ID as a URL parameter, or as a hidden element in a form…

Example 6.11. /app/controllers/posts_controller.php (partial)

//Here's how it would look if the URL param is used...
function addComment($post_id)
{
    if (!empty($this->data))
    {
        //You might want to make the $post_id data more safe,
        //but this will suffice for a working example..

        $this->data['Comment']['post_id'] = $post_id;

        //Because our Post hasMany Comments, we can access
        //the Comment model through the Post model:

        $this->Post->Comment->save($this->data);
    }
}


If the ID was passed as a hidden element in the form, you might want to name the field (if you’re using the HtmlHelper) so it ends up in the posted data where it needs to be:

If the ID for the post is at $post['Post']['id']...

<?php echo $html->hidden('Comment/post_id', array('value' => $post['Post']['id'])); ?>

Done this way, the ID for the parent Post model can be accessed at $this->data['Comment']['post_id'], and is all ready for a simple $this->Post->Comment->save($this->data) call.

These same basic techniques will work if you’re saving multiple child models, just place those save() calls in a loop (and remember to clear the model information using Model::create()).

In summary, if you’re saving associated data (for belongsTo, hasOne, and hasMany relations), the main point is getting the ID of the parent model and saving it to the child model.

Saving hasAndBelongsToMany Relations

Saving models that are associated by hasOne, belongsTo, and hasMany is pretty simple: you just populate the foreign key field with the ID of the associated model. Once that’s done, you just call the save() method on the model, and everything gets linked up correctly.

With hasAndBelongsToMany, its a bit trickier, but we’ve gone out of our way to make it as simple as possible. In keeping along with our example, we’ll need to make some sort of form that relates Tags to Posts. Let’s now create a form that creates posts, and associates them to an existing list of Tags.

You might actually like to create a form that creates new tags and associates them on the fly – but for simplicity’s sake, we’ll just show you how to associate them and let you take it from there.

When you’re saving a model on its own in Cake, the tag name (if you’re using the Html Helper) looks like ‘Model/field_name’. Let’s just start out with the part of the form that creates our post:

Example 6.12. /app/views/posts/add.thtml Form for creating posts

<h1>Write a New Post</h1>
<table>
	<tr>
    	<td>Title:</td>
    	<td><?php echo $html->input('Post/title')?></td>
	</tr>
	<tr>
    	<td>Body:<td>
    	<td><?php echo $html->textarea('Post/body')?></td>
	</tr>
	<tr>
    	<td colspan="2">
        	<?php echo $html->hidden('Post/user_id', array('value'=>$this->controller->Session->read('User.id')))?>
			<?php echo $html->hidden('Post/status' , array('value'=>'0'))?>
			<?php echo $html->submit('Save Post')?>
    	</td>
	</tr>
</table>


The form as it stands now will just create Post records. Let’s add some code to allow us to bind a given Post to one or many Tags:

Example 6.13. /app/views/posts/add.thtml (Tag association code added)

<h1>Write a New Post</h1>
<table>
	<tr>
		<td>Title:</td>
		<td><?php echo $html->input('Post/title')?></td>
	</tr>
	<tr>
		<td>Body:</td>
		<td><?php echo $html->textarea('Post/body')?></td>
	</tr>
	<tr>
		<td>Related Tags:</td>
		<td><?php echo $html->selectTag('Tag/Tag', $tags, null, array('multiple' => 'multiple')) ?>
		</td>
	</tr>
	<tr>
		<td colspan="2">
			<?php echo $html->hidden('Post/user_id', array('value'=>$this->controller->Session->read('User.id')))?>
			<?php echo $html->hidden('Post/status' , array('value'=>'0'))?>
			<?php echo $html->submit('Save Post')?>
		</td>
	</tr>
</table>


In order for a call to $this->Post->save() in the controller to save the links between this new Post and its associated Tags, the name of the field must be in the form “Tag/Tag” (the rendered name attribute would look something like ‘data[ModelName][ModelName][]‘). The submitted data must be a single ID, or an array of IDs of linked records. Because we’re using a multiple select here, the submitted data for Tag/Tag will be an array of IDs.

The $tags variable here is just an array where the keys are the IDs of the possible Tags, and the values are the displayed names of the Tags in the multi-select element.

Changing Associations on the Fly using bindModel() and unbindModel()

You might occasionally wish to change model association information for exceptional situations when building your application. If your association settings in the model file are giving you too much (or not enough) information, you can use two model functions to bind and unbind model associations for your next find.

Let’s set up a few models so we can see how bindModel() and unbindModel() work. We’ll start with two models:

Example 6.14. leader.php and follower.php

<?php

class Leader extends AppModel
{
    var $name = 'Leader';

    var $hasMany = array(
        'Follower' => array(
            'className' => 'Follower',
            'order'     => 'Follower.rank'
        )
    );
}

?>

<?php

class Follower extends AppModel
{
    var $name = 'Follower';
}

?>


Now, in a LeadersController, we can use the find() method in the Leader Model to come up with a Leader and its associated followers. As you can see above, the association array in the Leader model defines a “Leader hasMany Followers” relationship. For demonstration purposes, let’s use unbindModel() to remove that association mid-controller.

Example 6.15. leaders_controller.php (partial)

function someAction()
{
    //This fetches Leaders, and their associated Followers
    $this->Leader->findAll();

    //Let's remove the hasMany...
    $this->Leader->unbindModel(array('hasMany' => array('Follower')));

    //Now a using a find function will return Leaders, with no Followers
    $this->Leader->findAll();

    //NOTE: unbindModel only affects the very next find function.
    //An additional find call will use the configured association information.

    //We've already used findAll() after unbindModel(), so this will fetch
    //Leaders with associated Followers once again...
    $this->Leader->findAll();
}


The unbindModel() function works similarly with other associations: just change the name of the association type and model classname. The basic usage for unbindModel() is:

Example 6.16. Generic unbindModel() example

$this->Model->unbindModel(array('associationType' => array('associatedModelClassName')));


Now that we’ve successfully removed an association on the fly, let’s add one. Our as-of-yet unprincipled Leader needs some associated Principles. The model file for our Principle model is bare, except for the var $name statement. Let’s associate some Principles to our Leader on the fly (but only for just the following find function call):

Example 6.17. leaders_controller.php (partial)

funciton anotherAction()
{
    //There is no Leader hasMany Principles in the leader.php model file, so
    //a find here, only fetches Leaders.
    $this->Leader->findAll();

    //Let's use bindModel() to add a new association to the Principle model:
    $this->Leader->bindModel(
        array('hasMany' => array(
                'Principle' => array(
                    'className' => 'Principle'
                )
            )
        )
    );

    //Now that we're associated correctly, we can use a single find function
    //to fetch Leaders with their associated principles:
    $this->Leader->findAll();
}


The bindModel() function can be handy for creating new assocations, but it can also be useful if you want to change the sorting or other parameters in a given association on the fly.

There you have it. The basic usage for bindModel is to encapsulate a normal association array inside an array who’s key is named after the type of assocation you are trying to create:

Example 6.18. Generic bindModel() example

$this->Model->bindModel(
        array('associationName' => array(
                'associatedModelClassName' => array(
                    // normal association keys go here...
                )
            )
        )
    );


Please note that your tables will need to be keyed correctly (or association array properly configured) to bind models on the fly.

from : manual cake php Associations

Tags Tags:
Categories: CakePHP
Posted By: asbin
Last Edit: 31 May 2009 @ 08 10 PM

EmailPermalinkComments (1)
 20 May 2009 @ 12:14 AM 

Sebelumnya saya ucapkan sugeng rawuh alias selamat datang di web blog saya. karena ini adalah blog baru saya…. hehehe… langsung aja kita akan mengulas tentang framework cake php.

pada cake dikenal dengan metodenya yang menggunakan MVC ( Model View Controller). apakah itu MVC….??

  1. MODEL,  Dalam cake framework  model adalah bagian yang penting jika website yang kita buat menggunakan koneksi ke database. meodel adalah bagian yang mempunyai peran dalam pengaksesan table-table dari database, model juga mempunyai peran untuk menentukan relasi table. ada beberapa fungsi relasi tabel dari model seperti relasi hasOne(satu ke satu), HasMany(satu ke banyak),BelongsTo(banyak ke satu),BelongsToMany(banyak ke banyak)…. dll. untuk pembahasan relasi akan saya bahas pada artikel selanjutnya.
  2. VIEW adalah bagian dari framework cake yang dipergunakan sebagai media tamiplan dari framework ini. bisa disebut juga sebagai output dari hasil pengolahan algoritma dari controller.
  3. CONTROLLER, adalah bagian yang mempunyai fungsi sebagai tempat algoritma di olah. pada controller alur kerja program php diatur meenurut kebutuhan. karena framework cake adalah frame work yang mengacu pada pemrograman objek maka  semua code dalam controller wajib menggunakan aturan-aturan yang ditentukan yaitu menggunakan class dan methode (function).

nah… setelah kita tau tentang cake. kita pelajari dari awal pnggunaannya.

//MENGINSTAL ENGINE CAKE PHP//

sebelum kita mulai menginstal temen2 perlu mendownload engine framework cake kemudian instal di server masing-masing.

  1. Download engine script
  2. extrak ke folder root masing-masing
  3. buat databese kemudian import data cake-amix.sql (file ada dalam file rar).
  4. buka folder  “cake_trainingappconfigdatabase.php” kemudian masukkan settingan user, pwd database sesuai setingan database di kmputer kamu.
  5. buka file httpd.conf pada folder bin di server kmu kemudian cari script “mod_rewrite”, jika ketemu hilangkan tanda # pada baris sript tersebut.
  6. restart apache server.
  7. kemudian buka folder cake_training lewat browser. jika muncul tulisan ”

    Your database configuration file is present.

    Cake is able to connect to the database.

    ” berarti instal framework cake sudah berhasil dan terkoneksi ke database.

  8. siap coding menggunakan framework cake

nah setelah engine jalan saatnya bermain-main dengan code cake php. alur pengeksekusian dari cake pertama mendeteksi class contoller, jika dideteksi ada konek ke database cake mendeteksi adanya class model, terahir cake mendeteksi adanya view.

  1. sekarang kita coba buat file baru di folder controller “cake_trainingappcontrollers” dengan nama cobas_controller.php, buka file ini masukkan code
    <?php

    class CobasController extends AppController {

    var $uses = array(‘Coba’);

    function index(){
    $this->set(‘team’, $this->Coba->findAll());
    }

    function view(){

    }

    }

    ?>

  2. buat file coba.php pada direktory “cake_trainingappmodel” kemudian masukkan script berikut :
    <?php

    class Coba extends AppModel {

    var $name = ‘Coba’;
    var $useTable = ‘teams’;

    }

    ?>

  3. Buat folder baru pada directory “cake_trainingappviews” dengan nama “cobas” . selanjutnya buat file index.thtml dan view.thtml dalam folder tersebut. pada file index.thtml tuliskan script <? echo”<pre>”; print_r($team);?>
  4. terahir untuk mengetahui program jalan masukkan url http://localhost/cake_training/cobas
  5. lihat apa yang terjadi………….

ok kamu sekarang dah bisa membuat satu halaman website denga nama coba….. selamat berkreasi dengan framework cake php. untuk materi relasi dan penggunaan ajax pada cake php akan dibahas di artikel selanjutnya. ok…??? pokoknya semangat….!!!!!!!!!

Tags Tags:
Categories: CakePHP
Posted By: asbin
Last Edit: 31 May 2009 @ 08 11 PM

EmailPermalinkComments (2)
\/ More Options ...
Change Theme...
  • Users » 1
  • Posts/Pages » 49
  • Comments » 50
Change Theme...
  • VoidVoid « Default
  • LifeLife
  • EarthEarth
  • WindWind
  • WaterWater
  • FireFire
  • LightLight

About



    No Child Pages.