<?xml version="1.0" encoding="UTF-8"?><!-- generator="wordpress.com" -->
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	>

<channel>
	<title>cakephp &amp;laquo; WordPress.com Tag Feed</title>
	<link>http://en.wordpress.com/tag/cakephp/</link>
	<description>Feed of posts on WordPress.com tagged "cakephp"</description>
	<pubDate>Tue, 01 Dec 2009 16:05:03 +0000</pubDate>

	<generator>http://en.wordpress.com/tags/</generator>
	<language>en</language>

<item>
<title><![CDATA[Menggunakan CMS atau Framework?]]></title>
<link>http://r1dh0angg0r0.wordpress.com/2009/11/30/menggunakan-cms-atau-framework/</link>
<pubDate>Mon, 30 Nov 2009 14:17:52 +0000</pubDate>
<dc:creator>Ridho Anggoro</dc:creator>
<guid>http://r1dh0angg0r0.wordpress.com/2009/11/30/menggunakan-cms-atau-framework/</guid>
<description><![CDATA[Saya termasuk orang yang mengembangkan website tanpa pernah membuatnya dari nol. Maksudnya, saya tid]]></description>
<content:encoded><![CDATA[<div class='snap_preview'><p>Saya termasuk orang yang mengembangkan website tanpa pernah membuatnya dari nol. Maksudnya, saya tidak membuat komponen dari website itu secara manual satu demi satu. Mulai dari arsitektur website, komponen modul, file uploader, user access, image manager, dll. Biasanya semua dilakukan dengan menggunakan <a href="http://blog.iorme.net/blog/post/tentang_model_view_controller">CMS</a> yang OpenSource, seperti <a href="http://wordpress.org/">WordPress</a> dan <a href="http://drupal.org/">Drupal</a> (jaman dulu juga termasuk PHPNuke). Biasanya memang saya melakukan modifikasi disana – sini agar website ini bisa bekerja sesuai keinginan. Umumnya akhirnya website tersebut akhirnya bisa berjalan sesuai harapan.</p>
<p>Tetapi kemudian datang masalah seperti berikut ini :</p>
<ol>
<li>Website tersebut membutuhkan galery foto dengan fasilitas slideshow.</li>
<li>Website tersebut membutuhkan katalog produk.</li>
<li>Website tersebut ingin mengimplementasikan fasilitas social network.</li>
<li>Website itu ingin menyediakan fasilitas bagi membernya untuk bisa mengupload file MP3. Dan tiap member nantinya bisa mengatur level akses terhadap file MP3 yang dia upload.</li>
<li>Website tersebut ingin mempunyai form yang terintegrasi untuk arsip wawancara.</li>
<li>dll</li>
</ol>
<p>Jika saya menggunakan CMS seperti Drupal. Mungkin hal ini masih bisa ditangani dengan ketersediaan modulnya yang sangat banyak. Atau jika memang modulnya belum tersedia, kita bisa membuat sendiri. Selain itu jika kurang puas, kita masih bisa melakukan oprek lebih dalam dengan menggunakan <a href="http://en.wikipedia.org/wiki/Application_programming_interface">API</a> yang disediakan Drupal. Dengan tujuan agar website ini sesuai dengan apa yang kita inginkan.</p>
<p>Tetapi, hal ini bisa jadi merupakan masalah baru. Tentunya kadangkala hal ini bisa menjadi solusi untuk satu masalah tetapi bukan tidak jarang malah menimbulkan masalah baru. Beberapa skenario yang sering terjadi :</p>
<ol>
<li>Modul untuk <a href="http://id.wikipedia.org/wiki/Sistem_manajemen_konten">CMS</a> tersedia. Tetapi ada bagian yang tidak sesuai, bahkan mungkin ada bagian yang akhirnya malah terasa mengganggu. Misal modul e-commerce dari Drupal menyediakan begitu banyak fasilitas yang pada kenyataannya tidak saya butuhkan. Sedangkan untuk beberapa bagian justru masih belum sesuai harapan. Dan untuk bisa merubah modul ini, kita harus memahami hampir kesuluruhan struktur modul ini. Ditambah pengetahuan tentang API dari Drupal.</li>
<li>Terlalu banyak pilihan modul. Misal modul untuk upload gambar di Drupal. Secara default tidak ada. Kita masih bisa menginstal modul tambahan, sehingga nantinya <a href="http://drupal.org/project/imagepicker">upload gambar di Drupal akan semudah di WordPress</a>. Tetapi ketika sampai di tahap theming, saya menyadari bahwa field untuk gambar hasil upload modul tersebut tidak bisa diakse langsung. Berbeda dengan image yang diupload menggunakan bantuan module <a href="http://drupal.org/project/imagefield">Image Field (CCK)</a>.</li>
<li>Dengan <a href="http://api.drupal.org/">API</a> yang disediakan, kadangkala kita masih membutuhkan pengetahuan tentang API lain. Dan pada akhirnya mau tidak mau saya harus mempelajari banyak API, hanya untuk mengetahui bagian mana dari API ini yang tepat untuk solusi masalah saya.</li>
<li>Salah satu hal yang paling sulit adalah merubah alur kerja dari website ini. Misal jika user ingin register, tidaklah langsung ditampilkan ke halaman register, tetapi harus melalui satu halaman polling terlebih dahulu. Untuk bisa mengimplementasikan ini, secara tidak langsung kita harus tahu alur kerja (workflow) dari CMS yang kita gunakan.</li>
<li>Butuh field yang custom untuk tiap post (tidak hanya field TITLE dan POST saja). Secara default WordPress menyediakan fasilitas Custom Fields, tetapi penggunaannya masih belum senyaman CCK di Drupal. Untuk itu harus dibuat modul sendiri.</li>
<li>dll</li>
</ol>
<p>Jika memang akhirnya saya ingin menjadi <a href="http://lullabot.com/">ahli dari CMS</a> tersebut, saya rasa tidak masalah untuk mengikuti solusi yang saya berikan di atas. Tetapi jika saya hanya ingin menggunakan CMS ini sebagai bantuan, sepertinya effort nya terlalu besar.</p>
<p>Bahkan tidak jarang saya merasa, ketika mempelajari semua API, hook, templating, konvensi, dll dari suatu CMS, effortnya mungkin sama besarnya dengan jika saya membangun website tersebut dari nol.</p>
<p>Jadi apakah akhirnya membuat CMS dari nol?</p>
<p>Tidak. Bagi saya tetap tidak. Karena ada beberapa kemudahan di CMS yang tidak saya dapatkan jika saya harus membangun dari nol. Saya harus membangun kerangka / arsitektur dari website tersebut. Dan cukup banyak pula waktu yang tersita untuk membangunnya.</p>
<p>Jadi apa solusinya?</p>
<p>Framework. Bagi saya solusi di tengah – tengahnya adalah framework. Framework menjadi solusi yang tepat jika saya ingin mengembangkan website yang berbasis konten, tetapi dengan beberapa fasilitas yang tidak umum (seperti kasus di atas tadi). Dengan framework yang tepat, saya bisa membuat API saya sendiri, tetap mendapatkan fasilitas templating secara default, fasilitas layering untuk database, dan salah satu yang paling saya sukai adalah fasilitas URL Friendly secara default. Saya tidak tahu apakah semua framework menyediakan fasilitas tersebut, tetapi yang jelas Framework yang saya pakai (CodeIgniter) menggunakannya.</p>
<p>Pilihan framework yang cukup terkenal :</p>
<ol>
<li><a href="http://www.pradosoft.com/">Prado</a> – PHP (contoh : <a href="http://www.ui.edu/">website Univertias Indonesia</a>) : Kalau tidak salah ini seperti menjadi ASP.Net pada PHP</li>
<li><a href="http://codeigniter.com/">CodeIgniter</a> –  PHP(contoh : <a href="http://okezone.com/">OkeZone.com</a>), Jujur saja, saya tahu CodeIgniter dari situs OkeZone ini, dan sampai saat ini paling nyaman menggunakan ini, karena framework ini terdokumentasi dengan baik.</li>
<li><a href="http://www.rubyonrails.org/">Ruby On Rails</a> – Ruby (contoh : <a href="http://sharingfoto.com/">SharingFoto.com</a>) : Situs ini diklaim sebagai web aplikasi pertama di Indonesia yang menggunakan Ruby On Rails.</li>
<li><a href="http://cakephp.org/">CakePHP</a> – PHP (contoh : <a href="http://owncafe.com/">OwnCafe.com</a>) : Salah seorang yang sangat aktif dalam edukasi CakePHP di Indonesia adalah <a href="http://azzam.wordpress.com/">Sunu Wibirama</a> (alumni Teknik Elektro UGM). Situs lokal cake-php bisa dilihat di <a href="http://idcake.web.id/">idcake.web.id</a></li>
<li><a href="http://www.symfony-project.org/">Symfony</a> (PHP), <a href="http://www.djangoproject.com/">Django</a> (Python), dll</li>
</ol>
<p>Saya sendiri masih penasaran dan menantikan Mambo CMS versi 5.0 yang akan menggunakan CakePHP sebagai basisnya. Dengan kondisi seperti itu, maka level kustomisasi bisa dilakukan dari tingkat yang paling dasar (langsung menggunakan framework),di lapis tengah (modul), maupun lapis akhir (theming).</p>
<p>Jika ada yang tertarik dengan framework – framework di atas, jangan lupa pahami satu istilah ini : <a href="http://www.id-joomla.com/content/view/182/41/">MVC (Model View Controller)</a></p>
<p>&#160;</p>
<p>source: <a title="http://okto.silaban.net/2008/02/website/menggunakan-cms-atau-framework/" href="http://okto.silaban.net/2008/02/website/menggunakan-cms-atau-framework/" target="_blank">http://okto.silaban.net/2008/02/website/menggunakan-cms-atau-framework/</a></p>
</div>]]></content:encoded>
</item>
<item>
<title><![CDATA[Validación de datos usando jQuery en CakePHP]]></title>
<link>http://rnstux.wordpress.com/2009/11/30/validacion-de-datos-usando-jquery-en-cakephp/</link>
<pubDate>Mon, 30 Nov 2009 03:02:46 +0000</pubDate>
<dc:creator>rnstux</dc:creator>
<guid>http://rnstux.wordpress.com/2009/11/30/validacion-de-datos-usando-jquery-en-cakephp/</guid>
<description><![CDATA[Vamos hacer la validación de datos usando un plugin de la librería jQuery para lograr un efecto como]]></description>
<content:encoded><![CDATA[<div class='snap_preview'><p>Vamos hacer la validación de datos usando un <a href="http://bassistance.de/jquery-plugins/jquery-plugin-validation/">plugin</a> de la librería jQuery para lograr <a href="http://jquery.bassistance.de/validate/demo/">un efecto como este</a> utilizando CakePHP. Este tutorial esta basado en <a href="http://docs.jquery.com/Plugins/Validation">la documentación del plugin</a> ahí viene un ejemplo además de toda la documentación.</p>
<p><strong>Requerimientos: </strong></p>
<p><strong>Jquery.js</strong></p>
<p><strong>Jquery.form.js</strong></p>
<p><strong>Jquery.metadata.js</strong></p>
<p><strong>Jquery.validate.js</strong></p>
<p>Los puden buscar usando google o descargarlos de aquí,  pueden descargar de aquí:</p>
<p>http://rapidshare.com/files/264126244/Plugins.rar.html</p>
<p><strong> </strong><strong>Paso 1:</strong></p>
<p>Colocamos los 4 archivos dentro de la siguiente ruta;</p>
<p><strong>\app\webroot\js\validate</strong></p>
<p><strong> </strong>Creamos una tabla de ejemplo, en este caso es para PostgreSQL</p>
<p><strong>CREATE TABLE servicios(</strong></p>
<p><strong>id SERIAL PRIMARY KEY, </strong></p>
<p><strong>nombre VARCHAR(20) NOT NULL,</strong></p>
<p><strong>descripcion VARCHAR(60) NOT NULL,</strong></p>
<p><strong>status SMALLINT DEFAULT 0</strong></p>
<p><strong>); </strong></p>
<p><strong> </strong><strong>EL MODELO: </strong>En el modelo ya no es necesario que se le agregar el arreglo validate, tuve problemas al ponerlo, por eso es mejor quitarlo J <strong> </strong></p>
<p><strong> </strong><strong>&#60;?php</strong></p>
<p><strong> </strong><strong>class Servicio extends AppModel{</strong><strong>}</strong></p>
<p><strong> </strong><strong>?&#62;</strong></p>
<p><strong></strong><strong>EL CONTROLADOR: </strong>El controlador contiene la misma lógica, únicamente declaramos que vamos a emplear el helper Javascript<strong></strong></p>
<p><strong> </strong><strong>&#60;?php</strong></p>
<p><strong> </strong><strong>/**</strong></p>
<p><strong> * @author rnstux</strong></p>
<p><strong> * @copyright 2009</strong></p>
<p><strong> */</strong></p>
<p><strong>class ServiciosController extends AppController {</strong></p>
<p><strong> </strong><strong> var $name = &#8216;Servicios&#8217;;</strong></p>
<p><strong> var $helpers = array(&#8216;Html&#8217;, &#8216;Form&#8217;, &#8216;Javascript&#8217;);</strong></p>
<p><strong> </strong><strong> function add() {</strong></p>
<p><strong> if(!empty($this-&#62;data)){</strong></p>
<p><strong> if ($this-&#62;Servicio-&#62;save($this-&#62;data['Servicio'])){</strong></p>
<p><strong> $this-&#62;Session-&#62;setFlash(__(&#8216;Guardado.&#8217;, true));</strong></p>
<p><strong> </strong><strong> }else {</strong><strong> $this-&#62;Session-&#62;setFlash(__(&#8216;Ocurrio un error.&#8217;, true));}</strong><strong> </strong></p>
<p><strong> } </strong></p>
<p><strong> }</strong></p>
<p><strong> ?&#62;</strong><strong> </strong></p>
<p><strong>LA VISTA</strong><strong>: </strong>La vista es la parte mas importante, ahí vamos a agregar los archivos las librerías de Javascript a utilizar, el css, y el formulario sobre el cual se va a hacer la validación.</p>
<p><strong> </strong><strong> views/servicios/add.ctp</strong></p>
<p><strong> </strong><strong>&#60;?php</strong></p>
<p><strong> if (isset($javascript)) {</strong></p>
<p><strong> $javascript-&#62;link(array(</strong></p>
<p><strong> &#8216;jquery/jquery.validate&#8217;,</strong></p>
<p><strong> &#8216;validate/jquery.metadata&#8217;,</strong></p>
<p><strong> &#8216;validate/jquery.form&#8217;,</strong></p>
<p><strong> </strong><strong>&#8216;validate/jquery&#8217;</strong></p>
<p><strong> </strong><strong>), false);</strong></p>
<p><strong> }</strong></p>
<p><strong>?&#62;</strong></p>
<p><strong>&#60;style&#62; </strong></p>
<p><strong>.error {</strong></p>
<p><strong>color: red;</strong></p>
<p><strong>font: 12pt verdana;</strong></p>
<p><strong>padding-left: 10px</strong></p>
<p><strong>}</strong></p>
<p><strong>&#60;/style&#62;</strong></p>
<p><strong> </strong><strong>&#60;script&#62;</strong></p>
<p><strong>$(document).ready(function() { </strong></p>
<p><strong> $(&#8220;#ServicioAddForm&#8221;).validate(); </strong></p>
<p><strong>});</strong></p>
<p><strong>&#60;/script&#62;</strong></p>
<p><strong> </strong><strong>&#60;div&#62;</strong></p>
<p><strong>&#60;?php echo $form-&#62;create();?&#62;</strong></p>
<p><strong> &#60;fieldset&#62;</strong></p>
<p><strong> &#60;?php</strong></p>
<p><strong> </strong><strong> echo $form-&#62;input(&#8216;nombre&#8217;, array(&#8216;class&#8217;=&#62;&#8217;required&#8217;)); </strong></p>
<p><strong> echo $form-&#62;input(&#8216;descripcion&#8217;, array(&#8216;class&#8217;=&#62;&#8217;required&#8217;));</strong></p>
<p><strong> ?&#62;</strong></p>
<p><strong> &#60;/fieldset&#62;</strong></p>
<p><strong>&#60;?php echo $form-&#62;end(__(&#8216;Enviar&#8217;, true));?&#62;</strong></p>
<p><strong>&#60;/div&#62;</strong></p>
<p><strong><br />
</strong><strong>EXPLICACIÓN</strong></p>
<p><strong><br />
</strong>En esta parte del código va el <strong>id</strong> del formulario, generalmente CakePHP lo nombre de la siguiente manera: ModeloMetodoForm, en este caso: <strong>ServicioAddForm, </strong>ese es el nombre que se le pondra en estar parte de la vista</p>
<p><strong> </strong><strong>&#60;script&#62;</strong></p>
<p><strong>$(document).ready(function() { </strong></p>
<p><strong> $(&#8220;#ServicioAddForm&#8221;).validate(); </strong></p>
<p><strong>});</strong></p>
<p><strong>&#60;/script&#62;</strong></p>
<p><strong> </strong>Ahora tenemos que preparar los inputs para agregarles el tipo de dato valido para ellos, eso lo hacemos simplemente agregándole el atributo class y posteriormente la regla de validación a satisfacer ejem: required, required email, etc.</p>
<p>Y lo hacemos de la siguiente manera;</p>
<p><strong> echo $form-&#62;input(&#8216;nombre&#8217;, array(&#8216;class&#8217;=&#62;&#8217;required&#8217;)); </strong></p>
<p><strong> echo $form-&#62;input(&#8216;descripcion&#8217;, array(&#8216;class&#8217;=&#62;&#8217;required&#8217;));</strong></p>
<p>Después de la palabra ‘class’ viene la regla de validación, algunos ejemplos pueden ser:</p>
<p><strong>required</strong></p>
<p><strong>required email</strong></p>
<p><strong>url</strong></p>
<p>Para españolizar los mensajes que manda, podemos modificar el plugin jquery.validate.</p>
<p>That’s it!</p>
</div>]]></content:encoded>
</item>
<item>
<title><![CDATA[AuthCompornent 決着]]></title>
<link>http://yashio.wordpress.com/2009/11/26/authcompornent-%e6%b1%ba%e7%9d%80/</link>
<pubDate>Wed, 25 Nov 2009 15:46:11 +0000</pubDate>
<dc:creator>yashio</dc:creator>
<guid>http://yashio.wordpress.com/2009/11/26/authcompornent-%e6%b1%ba%e7%9d%80/</guid>
<description><![CDATA[わからなくてもういやだ＞＜だったAuthCompornent。 正直、タイプミスとかで動かないのかと思ってたけど、認識がそもそも…。な事が原因だった。 前回のブログだと何がしたいのか、わかりづらいので]]></description>
<content:encoded><![CDATA[<div class='snap_preview'><p>わからなくてもういやだ＞＜だったAuthCompornent。<br />
正直、タイプミスとかで動かないのかと思ってたけど、認識がそもそも…。な事が原因だった。</p>
<p>前回のブログだと何がしたいのか、わかりづらいので、まとめる。<br />
<strong>やりたかった事</strong></p>
<li>ユーザをつくる。ユーザは、グループA、グループBのどちらかに属す。（Aモデル、Bモデル）。</li>
<li>ユーザを作成したあとに、ログインすると自分が属しているページに遷移したい。</li>
<li>A組の人はA/index,B組の人はB/indexに遷移したい。</li>
<p>→そのためには、AuthCompornentを利用し、ログイン後にリダイレクト先を操作したい。<br />
<strong>やったこと</strong></p>
<li>標準的なusersテーブルを作成。</li>
<li>Aモデル、Bモデルは実装しないで$scaffoldで組み立てる。</li>
<li>usersテーブルには、mail,password,kindなぞを持たせる。認証はmail,passwordで。</li>
<li>AuthCompornentの認証としてはmail,passwordをつかう。</li>
<li>基本的な設定はapp/app_controller.phpのbeforeFilter();で記述する。</li>
<li>users_contoroller.phpでparent::beforeFilter();を呼ぶ。</li>
<p><strong>できなかったこと</strong></p>
<li>ログイン後、認証データからユーザ情報のkindを判断し、A組かB組かでリダイレクト先を制御。</li>
<p>認証自体の動きはできていたが、認証後、ユーザーの情報を取得することができなかった。<br />
ここでつまづいた。<br />
さて昨日のソースコードですが、わかりづらかったのでコメントでこのようにしてみました。</p>
<pre class="brush: php;">
class UsersController extends AppController {

//start　ここから重要な箇所
	  var $name = 'Users';
	  var $helpers = array('Html', 'Form');

	  function beforeFilter() {
	    parent::beforeFilter();
	    $this-&#62;Auth-&#62;allow('add');
	    $user = $this-&#62;Auth-&#62;user();//AuthComponent;
        //問題の箇所。ここで振り分ける処理をかいたが、動かない。
 	if($user['User']['kind']=='1'){
   		$this-&#62;redirect('/companies/index');
   	}elseif($user['User']['kind']=='2'){
   		$this-&#62;redirect('/members/index');
   	}  

　　　//ここでかいても、nullだの言われる。
　　　var_dump($user);
	   }

	  function login(){
	  }
//ここまでが重要なコード。以下はどうでも良い。
	  function logout(){
	    $this-&#62;Session-&#62;setFlash('ログアウトしました');
	    $this-&#62;Auth-&#62;logout();
	    $this-&#62;redirect(array('action' =&#62; 'login'));
	  }

	  function add() {
	    if (!empty($this-&#62;data)) {
	        $this-&#62;User-&#62;create();
	        $this-&#62;User-&#62;save($this-&#62;data['User']);
	        //登録ユーザーでその後の登録ページを遷移する
	        if($this-&#62;data['User']['kind']==0){
	            $this-&#62;redirect('/companies/add');
	        }elseif($this-&#62;data['User']['kind']==1){
	            $this-&#62;redirect('/members/add');
	        }
	    }
	  }
}
</pre>
<p>ここで、読者の方は「…そこで書いてもだめでしょ…」とすでにお気づきなんだとは思うのですが、許して＞＜<br />
ここ、だいぶ躓きました。beforeFilterの中でリダイレクト先を指定するコードをかくためにそこで認証データを参照するのですが、<br />
参照しても参照しても、現在ログインしているユーザの情報が取得できない。<br />
・セッションをクリアする<br />
・Aさんでログインする（kind==1の人）<br />
・リダイレクトは本来ならcompanies/indexに飛んでほしいけど飛ばない（上記のソースでいえばifにもelseifにもはいらない）。<br />
・ログイン画面に戻って、Bさん(kind==0の人）でログインする<br />
・ログインするとAさん（Bさんじゃないのかよ）が飛ぶべきログイン先（companies/index)にリダイレクトする</p>
<p>というように、「１世代古い状態」でなぜかリダイレクトを参照するという状況になり、大変なことに。（メンタル）</p>
<p>ここで「…なにこれ」と思って月曜から悩んで今日に至ったわけですが、賢明な読者の方はお気づきでしょうが、<br />
<strong>beforeFilter()内ではまだ認証は行われていないのでとりようがない</strong>ということに気がつくのに２日かかったという…。<br />
きがついた原因としては<a href="http://blog.ne2ma2.com/archives/163">ねねとまつの小部屋</a>でのコードでした。<br />
多分このソースをまるごとコピーして作成していたらまた違ったとおもうのですが、リダイレクトの処理については見落としていました。<br />
標準的なブログはログイン後のリダイレクトについてどこにかくべきかなんて名言してないですよね。いやログインした後のログイン先を認証データで判断するということ自体があまり必要のないことなのではないかと思います。ログイン認証時のデータを参照する必要がなければbeforeFilter()に設定するので問題ないのですから。</p>
<p>app_contorollerにかこうが、users_controllerにかこうが、ログイン認証を行った後の認証データを参照したい場合はbeforeFilterではなく、app_controllerのlogin()内にかかなくてはいけないのです。…はい。一世代ログイン情報が古かったのはbeforeFilterで参照していたものは、「すでにログインしたとみなされたふるい認証データ」だったということになります。つ、ま、り。</p>
<pre class="brush: php;">
&#60;?php
class UsersController extends AppController {
  var $name = 'Users';
  var $helpers = array('Html', 'Form');

  function beforeFilter() {
//ここではまだ認証を通っていない。ここで参照しようとすると残って（いれば）過去の認証データが参照できる。意味なし。
  	parent::beforeFilter();
    $this-&#62;Auth-&#62;allow('add');
  }

  function login(){
//ここで初めて最新のログイン認証を通ったユーザーの情報が取得できる。
	$user = $this-&#62;Auth-&#62;user();
  	if($user['User']['kind']=='1'){
   		$this-&#62;redirect('/companies/index');
   	}elseif($user['User']['kind']=='0'){
   		$this-&#62;redirect('/members/index');
   	}
  }

  function logout(){
    $this-&#62;Session-&#62;setFlash('ログアウトしました');
    $this-&#62;Auth-&#62;logout();
    $this-&#62;redirect(array('action' =&#62; 'login'));
  }

  function add() {
    if (!empty($this-&#62;data)) {
        $this-&#62;User-&#62;create();
        $this-&#62;User-&#62;save($this-&#62;data['User']);
        //登録ユーザーでその後の登録ページを遷移する
        if($this-&#62;data['User']['kind']==0){
        	$this-&#62;redirect('/companies/add');
        }elseif($this-&#62;data['User']['kind']==1){
        	$this-&#62;redirect('/members/add');
        }
    }
  }
}
</pre>
<p>てな具合に。一応app/の上位のAppController も乗せておく。</p>
<pre class="brush: php;">
&#60;?php
class AppController extends Controller {
	//var $components = array('Auth');
	var $components = array('Auth','DebugKit.Toolbar');
	var $user;

	function beforeFilter(){
		//リダイレクトを指定したいのでfalseに指定する
		$this-&#62;Auth-&#62;autoRedirect=false;
		$this-&#62;Auth-&#62;fields = array('username' =&#62; 'mail','password' =&#62; 'password');
		$this-&#62;set('user',$this-&#62;Auth-&#62;user());
		$this-&#62;Auth-&#62;loginError = 'ログインエラー';
		$this-&#62;Auth-&#62;authError = 'ログインしていません';
	}
}
?&#62;
</pre>
<p>このようにすることで、ログイン認証を行ったあとのユーザ情報を正確に取得することができました。<br />
AuthCompornentの動きで、ユーザがログインした場合Autn-&#62;login()が呼び出されるタイミングが自分の中でわかっていなかったのが原因ですね。・・・。users_contorollerにはlogin()はあったのですが、中身はなかった。器だけ用意しとけばいいだろと思っていたので、明確に根拠はなかったのですが、AppControllerのbeforeFilterで呼び出されるようなきがしていました。今も実は根拠はない。実際に動かしてみたらlogin()では参照できたのでそこで初めて参照できる、という事実を知っただけですが・・。<br />
あたりまえですが、beforeFilterというのはbeforeFilterなんだよね…。AuthCompornentが実際にログイン処理を行っているタイミングがいまいち把握できていないことが理由で、下らんことに時間をかけてしまった…。。。。。</p>
<p>もし、この記事で同じようなことに遭遇した人がいたら、そうよね！そうよね！と分かち合いたい。そんな人いないか…。<br />
タイプミスで動きませんでした；；のほうが格好よかったかもしれない。今後、開発で難儀しそうだなあ…、、、とほほ。<br />
週末、もうちょっと遷移を進めてみることにしよう。</p>
</div>]]></content:encoded>
</item>
<item>
<title><![CDATA[AuthCompornent　ログイン後のリダイレクト編]]></title>
<link>http://yashio.wordpress.com/2009/11/24/authcompornent%e3%80%80%e3%83%ad%e3%82%b0%e3%82%a4%e3%83%b3%e5%be%8c%e3%81%ae%e3%83%aa%e3%83%80%e3%82%a4%e3%83%ac%e3%82%af%e3%83%88%e7%b7%a8/</link>
<pubDate>Tue, 24 Nov 2009 14:07:49 +0000</pubDate>
<dc:creator>yashio</dc:creator>
<guid>http://yashio.wordpress.com/2009/11/24/authcompornent%e3%80%80%e3%83%ad%e3%82%b0%e3%82%a4%e3%83%b3%e5%be%8c%e3%81%ae%e3%83%aa%e3%83%80%e3%82%a4%e3%83%ac%e3%82%af%e3%83%88%e7%b7%a8/</guid>
<description><![CDATA[なんでかわからないのでとりあえずメモ。 ごくごく、簡単なログイン認証のAuthCompornentを使用して、ログイン認証を作成します。 ・Userを作成 Userには id ,mail ,passw]]></description>
<content:encoded><![CDATA[<div class='snap_preview'><p>なんでかわからないのでとりあえずメモ。<br />
ごくごく、簡単なログイン認証のAuthCompornentを使用して、ログイン認証を作成します。<br />
・Userを作成<br />
Userには<br />
id ,mail ,password,kind,created ,modified　<br />
で構成されているテーブル。ユーザー登録はできる。パスワードもハッシュ化。ここまでは順調。(mailとpasswordで認証）<br />
ここで、作成したユーザーが、ログインを行った場合、登録されているUserテーブルのkindフィールドを見る。<br />
kind=0 の場合は/aaa/index　にリダイレクトしたい。<br />
kind=1の場合は/bbb/index　　というように、ログインしたユーザーのkindフィールドの値でリダイレクト先を振り分けたい、というのが目的。ところが、下記のソースでbeforeFilter内で振り分けられるのかな、と思ったが、なんと<br />
$user = $this-&#62;Auth-&#62;user();<br />
ここで$userデータがどうも、取れてきていない…。<br />
$user['User']['kind']で値がとれてきてるのかなーって思ったんだけど、どうも$user自体が取得できていない。<br />
logout()を呼び出して認証をクリアしてから、再度ログイン画面でログインを行うと、この$userデータがなんと、null。<br />
なんか、ものすごおぉく些細な事でつまづいてるきがするんだけども。<br />
ちなみに、現在users/loginを表示したときに現在の認証状態をクリアする処理がされていないので<br />
一度ログインしちゃうとURLでlogoutを呼び出さないと認証状態が新しいものにならない…のかな。<br />
原因としてはこっちに問題があるのかなあ。<br />
認証をクリアした場合、対象のuserテーブルの内容が全部$this-&#62;Authから参照できるのかと思ってるんだけどなー。<br />
さて風呂はいってくっか。</p>
<pre class="brush: php;">
class UsersController extends AppController {
  var $name = 'Users';
  var $helpers = array('Html', 'Form');

  function beforeFilter() {
  	parent::beforeFilter();
    $this-&#62;Auth-&#62;allow('add');
    $user = $this-&#62;Auth-&#62;user();//AuthComponent
    $this-&#62;redirect('/members/add');
   }

  function login(){
  }
  function logout(){
    $this-&#62;Session-&#62;setFlash('ログアウトしました');
    $this-&#62;Auth-&#62;logout();
    $this-&#62;redirect(array('action' =&#62; 'login'));
  }

  function add() {
    if (!empty($this-&#62;data)) {
        $this-&#62;User-&#62;create();
        $this-&#62;User-&#62;save($this-&#62;data['User']);
        //登録ユーザーでその後の登録ページを遷移する
        if($this-&#62;data['User']['kind']==0){
        	$this-&#62;redirect('/companies/add');
        }elseif($this-&#62;data['User']['kind']==1){
        	$this-&#62;redirect('/members/add');
        }
    }
  }
}
</pre>
</div>]]></content:encoded>
</item>
<item>
<title><![CDATA[Phân trang (pagination) cho nhiều model trong cùng 1 trang]]></title>
<link>http://truongtronghai.wordpress.com/2009/11/24/phan-trang-pagination-cho-nhi%e1%bb%81u-model-trong-cung-1-trang/</link>
<pubDate>Tue, 24 Nov 2009 04:57:37 +0000</pubDate>
<dc:creator>truongtronghai</dc:creator>
<guid>http://truongtronghai.wordpress.com/2009/11/24/phan-trang-pagination-cho-nhi%e1%bb%81u-model-trong-cung-1-trang/</guid>
<description><![CDATA[Nếu bạn là người đã từng sử  dụng cakePHP thì chắc chắn bạn sẽ đồng ý với tôi là cakePHP làm rất tốt]]></description>
<content:encoded><![CDATA[<div class='snap_preview'><p>Nếu bạn là người đã từng sử  dụng cakePHP thì chắc chắn bạn sẽ đồng ý với tôi là cakePHP làm rất tốt việc phân trang dữ liệu trình bày trên web. Đối với tôi nó giúp tiết kiệm rất nhiều thời gian cho việc xây dựng web. Tuy nhiên, nếu trên 1 trang bạn cần nhiều hơn 1 vùng phân trang thì sao? Td: bạn có trang web trên đó cần trình bày danh sách người dùng ( model User ) và nhóm người dùng ( model Group ) trong khi ở view bạn chỉ có 1 đối tượgn paginator ( dùng để phân trang ) . Tôi đã gặp vấn đề này và cũng mất không ít thời gian để dán mắt vào Google tìm cách giải quyết và thật may mắn tôi đã tìm thấy bài viết của tác giả <a href="http://debuggable.com/about">Tim Koschützki</a> để có được lời giải cho vấn đề này. Hãy xem bài viết <a href="http://debuggable.com/posts/how-to-have-multiple-paginated-widgets-on-the-same-page-with-cakephp:48ad241e-b018-4532-a748-0ec74834cda3" target="_blank">tại đây</a>.</p>
<p>Chúc bạn thành công.</p>
</div>]]></content:encoded>
</item>
<item>
<title><![CDATA[Nhiều form thực hiện submit đến cùng 1 controller]]></title>
<link>http://truongtronghai.wordpress.com/2009/11/24/nhi%e1%bb%81u-form-th%e1%bb%b1c-hi%e1%bb%87n-submit-d%e1%ba%bfn-cung-1-controller/</link>
<pubDate>Tue, 24 Nov 2009 04:46:55 +0000</pubDate>
<dc:creator>truongtronghai</dc:creator>
<guid>http://truongtronghai.wordpress.com/2009/11/24/nhi%e1%bb%81u-form-th%e1%bb%b1c-hi%e1%bb%87n-submit-d%e1%ba%bfn-cung-1-controller/</guid>
<description><![CDATA[Trong quá trình xây dựng web tôi gặp phải trường hợp cần đặt 2 ( hay nhiều ) form trên cùng 1 trang.]]></description>
<content:encoded><![CDATA[<div class='snap_preview'><p>Trong quá trình xây dựng web tôi gặp phải trường hợp cần đặt 2 ( hay nhiều ) form trên cùng 1 trang. Vấn đề sẽ nảy sinh khi các form này submit dữ liệu về các action khác nhau nhưng của cùng 1 controller. Khi đó, đối với tất cả các form được vẽ ra bằng helper FORM, khi bạn submit ở bất cứ form nào thì dữ liệu đều đưa về action của form đầu tiên <img src='http://s.wordpress.com/wp-includes/images/smilies/icon_sad.gif' alt=':(' class='wp-smiley' />  Thí dụ: tôi có 1 controller tên mains , trong đó có 2 action: search ( tìm kiếm trên web ) và signup ( cho người dùng tiến hành đăng ký ). Vì search luôn nằm trên khu vực header và signup nằm ở content , nghĩa form search là form đầu tiên trong trang.</p>
<p>Ở tình huống này, khi bạn submit ở form signup thì dữ liệu vẫn được đưa đến action search()</p>
<p>Tôi không hiểu được nguyên nhân tại sao nhưng giải pháp tôi đã sử  dụng để giải quyết vấn đề này là tôi chỉ sử dụng helper FORM 1 lần trong trang ( Td: để tạo ra form search ) còn các form khác thì tôi dùng HTML để vẽ ra như bình thường.</p>
</div>]]></content:encoded>
</item>
<item>
<title><![CDATA[PHP Framework - Siapa yang tercepat?]]></title>
<link>http://mul14.wordpress.com/2009/11/23/php-framework-siapa-yang-tercepat/</link>
<pubDate>Mon, 23 Nov 2009 11:05:25 +0000</pubDate>
<dc:creator>mul14</dc:creator>
<guid>http://mul14.wordpress.com/2009/11/23/php-framework-siapa-yang-tercepat/</guid>
<description><![CDATA[Kali ini saya membandingkan enam PHP Framework berbasis MVC (Model View Controller) yang populer. Ke]]></description>
<content:encoded><![CDATA[<div class='snap_preview'><p><img style="float:right;" src="http://d.yimg.com/gg/doophp/avatars/45ae52322e02e416e5d02221c5e31abdd9925032.png" alt="" /></p>
<p>Kali ini saya membandingkan enam PHP Framework berbasis MVC (Model View Controller) yang populer. Keenam framework itu adalah CakePHP, CodeIgniter, Kohana v2 dan v3, Yii, dan &#8220;new kid on the block&#8221; DooPHP. Semua menggunakan versi terbaru saat ini (2009-11-22) kecuali Yii. Berikut informasi detail mengenai versi yang di-test:<br />
- <a href="http://www.cakephp.org">Cake PHP</a> 1.2.5<br />
- <a href="http://www.codeigniter.com">Code Igniter</a> 1.7.2<br />
- <a href="http://www.kohanaphp.com">Kohana</a> 2.3.4<br />
- <a href="http://v3.kohanaphp.com">Kohana</a> 3.0.1.2<br />
- <a href="http://www.yiiframework.com">Yii</a> 1.0.10<br />
- <a href="http://www.doophp.com">Doo</a> 1.2</p>
<p>Mesin yang digunakan<br />
Acer Aspire 4520<br />
AMD Turion 64 X2 TL-58 1.9 GHz<br />
RAM 3 GiB</p>
<p>Software yang digunakan<br />
- Windows 7 Ultimate<br />
- <a href="http://httpd.apache.org">Apache</a> 2.2.12<br />
- <a href="http://id.php.net">PHP</a> 5.3</p>
<p>Hampir semua framework konfigurasi-nya tidak diubah sama sekali (kondisi default). Kecuali Cake PHP yang sudah dimatikan konfigurasi session, cache, database, log, dan debug.</p>
<p>Metode test yang digunakan mencetak tulisan &#8220;Hello World!&#8221; lalu langsung exit;.</p>
<p>Hasil yang didapat adalah nilai rata-rata dalam satuan rps (request per second). Berikut dari yang terlambat hingga yang tercepat:</p>
<blockquote><p>- CakePHP      ==&#62; 19.72 rps<br />
- CodeIgniter  ==&#62; 71.23 rps<br />
- Yii          ==&#62; 73.68 rps<br />
- Kohana v2    ==&#62; 76.31 rps<br />
- Kohana v3    ==&#62; 103.39 rps<br />
- Doo          ==&#62; 200.32 rps</p></blockquote>
<p>Terlihat Doo buatan negri tetangga adalah yang tercepat dalam test &#8220;Hello World!&#8221; ini.</p>
<p>Tapi dalam memilih suatu framework, bukan mana yang tercepat. Tapi yang paling nyaman anda gunakan sehingga mempersingkat waktu <em>developing</em> dan meningkatkan produktivitas anda.</p>
<p>Berikutnya akan ada tambahan dari PHP Framework berbasis MVC lainnya seperti <a href="http://www.symfony-project.org">Symfony</a>, <a href="http://framework.zend.com">Zend Framework</a>, dan <a href="http://adventure-php-framework.org">APF</a>, <a href="http://solarphp.com/">Solar Framework</a>. Dan agar lebih fair, semua session, cache, database, dll akan di-non aktifkan. &#8220;Hello World!&#8221; juga akan dicetak pada view, bukan pada controller lalu exit.</p>
<p>Nb: Konfigurasi module dan extension yang sedang berjalan pada Apache dan PHP tidak diikutsertakan dalam tulisan ini.</p>
</div>]]></content:encoded>
</item>
<item>
<title><![CDATA[CakePHP app กับ userdir]]></title>
<link>http://veer66.wordpress.com/2009/11/21/cake_userdir/</link>
<pubDate>Sat, 21 Nov 2009 09:55:35 +0000</pubDate>
<dc:creator>वीर</dc:creator>
<guid>http://veer66.wordpress.com/2009/11/21/cake_userdir/</guid>
<description><![CDATA[เวลาเอา web app ที่เขียนด้วย cakephp ไปใส่ใน userdir เช่น /home/veer/public_html/myapp (ซึ่งมักจะไปต]]></description>
<content:encoded><![CDATA[<div class='snap_preview'><p>เวลาเอา web app ที่เขียนด้วย cakephp ไปใส่ใน userdir เช่น /home/veer/public_html/myapp (ซึ่งมักจะไปตรงกับ url http://hostname/~veer/myapp) มักจะมีปัญหากับ mod_rewrite ขึ้นมา แต่ก็แก้ไม่ยาก เพียงแต่แก้ .htaccess ใน myapp  กับ myapp/app/webroot</p>
<p>เดิมทีจะเขียนไว้ประมาณนี้ (ใน myapp กับ myapp/app/webroot ไม่เหมือนกัน แต่ก็แก้เหมือนกัน)</p>
<pre>

   RewriteEngine on
   RewriteRule    ^$ app/webroot/    [L]
   RewriteRule    (.*) app/webroot/$1 [L]
</pre>
<p>ก็แก้โดยใส่ RewriteBase เข้าไปเป็นแบบนี้</p>
<pre>

   RewriteEngine on
   RewriteBase    /~veer/myapp
   RewriteRule    ^$ app/webroot/    [L]
   RewriteRule    (.*) app/webroot/$1 [L]
</pre>
<p>เสร็จแล้ว</p>
</div>]]></content:encoded>
</item>
<item>
<title><![CDATA[What is CamelCase?]]></title>
<link>http://changyuan28.wordpress.com/2009/11/19/what-is-camelcase/</link>
<pubDate>Fri, 20 Nov 2009 01:09:11 +0000</pubDate>
<dc:creator>Michael Chang</dc:creator>
<guid>http://changyuan28.wordpress.com/2009/11/19/what-is-camelcase/</guid>
<description><![CDATA[CamelCase (also spelled &#8220;camel case&#8221;) or medial capitals is the practice of writing comp]]></description>
<content:encoded><![CDATA[CamelCase (also spelled &#8220;camel case&#8221;) or medial capitals is the practice of writing comp]]></content:encoded>
</item>
<item>
<title><![CDATA[CakePHP ACL Tutorial - What]]></title>
<link>http://changyuan28.wordpress.com/2009/11/19/cakephp-acl-tutorial-what/</link>
<pubDate>Fri, 20 Nov 2009 01:08:36 +0000</pubDate>
<dc:creator>Michael Chang</dc:creator>
<guid>http://changyuan28.wordpress.com/2009/11/19/cakephp-acl-tutorial-what/</guid>
<description><![CDATA[ACL or Access Control List is security concept about permission. It’s contain a list of permission t]]></description>
<content:encoded><![CDATA[ACL or Access Control List is security concept about permission. It’s contain a list of permission t]]></content:encoded>
</item>
<item>
<title><![CDATA[Improved form handling in CakePHP 1.3]]></title>
<link>http://teknoid.wordpress.com/2009/11/17/improved-form-handling-in-cakephp-1-3/</link>
<pubDate>Tue, 17 Nov 2009 16:49:35 +0000</pubDate>
<dc:creator>teknoid</dc:creator>
<guid>http://teknoid.wordpress.com/2009/11/17/improved-form-handling-in-cakephp-1-3/</guid>
<description><![CDATA[Here is a typical, simple form done with cake&#8217;s form helpers: echo $this-&gt;Form-&gt;create(']]></description>
<content:encoded><![CDATA[<div class='snap_preview'><p>Here is a typical, simple form done with cake&#8217;s form helpers:</p>
<pre class="brush: php;">
echo $this-&#62;Form-&#62;create('Article', array('action' =&#62; 'test'));

echo $this-&#62;Form-&#62;input('Article.title');
echo $this-&#62;Form-&#62;input('Article.body');
echo $this-&#62;Form-&#62;input('Article.user_id', array('type' =&#62; 'hidden'));

echo $form-&#62;end('Add Aricle with Tags and Comment');
</pre>
<p>Which outputs the following HTML:</p>
<pre class="brush: xml;">
&#60;form id=&#34;ArticleTestForm&#34; method=&#34;post&#34; action=&#34;/articles/test&#34; accept-charset=&#34;utf-8&#34;&#62;
    &#60;fieldset style=&#34;display:none;&#34;&#62;
        &#60;input type=&#34;hidden&#34; name=&#34;_method&#34; value=&#34;POST&#34; /&#62;
    &#60;/fieldset&#62;
    &#60;div class=&#34;input text&#34;&#62;
        &#60;label for=&#34;ArticleTitle&#34;&#62;
            Title
        &#60;/label&#62;
        &#60;input name=&#34;data[Article][title]&#34; type=&#34;text&#34; maxlength=&#34;50&#34; value=&#34;&#34; id=&#34;ArticleTitle&#34; /&#62;
    &#60;/div&#62;
    &#60;div class=&#34;input textarea&#34;&#62;
        &#60;label for=&#34;ArticleBody&#34;&#62;
            Body
        &#60;/label&#62;
        &#60;textarea name=&#34;data[Article][body]&#34; cols=&#34;30&#34; rows=&#34;6&#34; id=&#34;ArticleBody&#34;&#62;
        &#60;/textarea&#62;
    &#60;/div&#62;
    &#60;input type=&#34;hidden&#34; name=&#34;data[Article][user_id]&#34; value=&#34;&#34; id=&#34;ArticleUserId&#34; /&#62;
    &#60;div class=&#34;submit&#34;&#62;
        &#60;input type=&#34;submit&#34; value=&#34;Add Aricle with Tags and Comment&#34; /&#62;
    &#60;/div&#62;
&#60;/form&#62;
</pre>
<p>This is fine and all, but one thing worth noting is that default behavior is wrapping each element in a <code>div</code>, and in some cases this may not be desirable. Either a legacy CSS or a front-end developer preference, might require the form to be structured (wrapped) differently.</p>
<p>Let&#8217;s see how we can set some defaults for our form with CakePHP 1.3., while simplifying the code a little at the same time by using the <code>inputs()</code> method&#8230;</p>
<pre class="brush: php;">
 echo $this-&#62;Form-&#62;create('Article', array('action' =&#62; 'test',
                                              'inputDefaults' =&#62; array(
                                                'div' =&#62; array('tag' =&#62; 'p'),
                                                'before' =&#62; '-- goes before the label --',
                                                'after' =&#62; '-- goes after the input --')));    

echo $this-&#62;Form-&#62;inputs(array('Article.title',
                                               'Article.body',
                                               'Article.user_id' =&#62; array('type' =&#62; 'hidden')),
                                      array('legend' =&#62; 'Article submit'));

echo $this-&#62;Form-&#62;end('Add Aricle');
</pre>
<p>Which produces:</p>
<pre class="brush: php;">
&#60;form id=&#34;ArticleTestForm&#34; method=&#34;post&#34; action=&#34;/articles/test&#34; accept-charset=&#34;utf-8&#34;&#62;
    &#60;fieldset style=&#34;display:none;&#34;&#62;
        &#60;input type=&#34;hidden&#34; name=&#34;_method&#34; value=&#34;POST&#34; /&#62;
    &#60;/fieldset&#62;
    &#60;fieldset&#62;
        &#60;legend&#62;
            New Article
        &#60;/legend&#62;
        &#60;p class=&#34;input text&#34;&#62;
            -- goes before the label --
            &#60;label for=&#34;ArticleTitle&#34;&#62;
                Title
            &#60;/label&#62;
            &#60;input name=&#34;data[Article][title]&#34; type=&#34;text&#34; maxlength=&#34;50&#34; value=&#34;&#34; id=&#34;ArticleTitle&#34; /&#62;
           -- goes after the input --
        &#60;/p&#62;
        &#60;p class=&#34;input textarea&#34;&#62;
            -- goes before the label --
            &#60;label for=&#34;ArticleBody&#34;&#62;
                Body
            &#60;/label&#62;
            &#60;textarea name=&#34;data[Article][body]&#34; cols=&#34;30&#34; rows=&#34;6&#34; id=&#34;ArticleBody&#34;&#62;
            &#60;/textarea&#62;
           -- goes after the input --
        &#60;/p&#62;
        &#60;input type=&#34;hidden&#34; name=&#34;data[Article][user_id]&#34; value=&#34;&#34; id=&#34;ArticleUserId&#34; /&#62;
    &#60;/fieldset&#62;
    &#60;div class=&#34;submit&#34;&#62;
        &#60;input type=&#34;submit&#34; value=&#34;Add Aricle&#34; /&#62;
    &#60;/div&#62;
&#60;/form&#62;
</pre>
<p>Of course for a simple form this may not be a very significant improvement, but having the ability to set defaults for the entire form and relying on some automagic for the rest, certainly makes one&#8217;s life easier.</p>
</div>]]></content:encoded>
</item>
<item>
<title><![CDATA[Scope Behavior]]></title>
<link>http://evilbloodydemon.wordpress.com/2009/11/16/scope-behavior/</link>
<pubDate>Mon, 16 Nov 2009 09:50:18 +0000</pubDate>
<dc:creator>evilbloodydemon</dc:creator>
<guid>http://evilbloodydemon.wordpress.com/2009/11/16/scope-behavior/</guid>
<description><![CDATA[У меня возникла такая ситуация, что несколько сайтов с одинаковым движком используют одни и те же та]]></description>
<content:encoded><![CDATA[<div class='snap_preview'><p>У меня возникла такая ситуация, что несколько сайтов с одинаковым движком используют одни и те же таблицы в одной базе данных. Для различения принадлежности записей в бд к сайтам используется поле <strong>site_id</strong>. Добавлять его к каждому запросу в условия довольно утомительно, поэтому я сделал специальный behavior для этой цели &#8211; Scope.</p>
<p>в модели (например, User) добавляем behavior и передаем ему настройки</p>
<pre>
<pre style="background-color:#ffffff;width:100%;font-family:consolas,&#39;font-size:12px;margin:0;"><span style="color:#0000ff;">&#60;?</span>php
</pre>
<pre style="background-color:#ffffff;width:100%;font-family:consolas,&#39;font-size:12px;margin:0;">...
</pre>
<pre style="background-color:#ffffff;width:100%;font-family:consolas,&#39;font-size:12px;margin:0;"><a style="color:#0000ff;" href="http://www.php.net/var">var</a> $actsAs = <a style="color:#ffa500;" href="http://www.php.net/array">array</a>(
</pre>
<pre style="background-color:#ffffff;width:100%;font-family:consolas,&#39;font-size:12px;margin:0;">    '<span style="color:#8b0000;">Scope.Scope</span>' =&#62; <a style="color:#ffa500;" href="http://www.php.net/array">array</a>(
</pre>
<pre style="background-color:#ffffff;width:100%;font-family:consolas,&#39;font-size:12px;margin:0;">        '<span style="color:#8b0000;">field</span>' =&#62; '<span style="color:#8b0000;">site_id</span>',
</pre>
<pre style="background-color:#ffffff;width:100%;font-family:consolas,&#39;font-size:12px;margin:0;">        '<span style="color:#8b0000;">value</span>' =&#62; SITE_ID,
</pre>
<pre style="background-color:#ffffff;width:100%;font-family:consolas,&#39;font-size:12px;margin:0;">    )
</pre>
<pre style="background-color:#ffffff;width:100%;font-family:consolas,&#39;font-size:12px;margin:0;">);
</pre>
<pre style="background-color:#ffffff;width:100%;font-family:consolas,&#39;font-size:12px;margin:0;">...
</pre>
<pre style="background-color:#ffffff;width:100%;font-family:consolas,&#39;font-size:12px;margin:0;"><span style="color:#0000ff;">?&#62;</span></pre>
</pre>
<p>&#160;</p>
<p>теперь при вызове функций модели find или save условие будет добавляться автоматически, то есть</p>
<pre>
<pre style="background-color:#ffffff;width:100%;font-family:consolas,&#39;font-size:12px;margin:0;"><span style="color:#0000ff;">&#60;?</span>php
</pre>
<pre style="background-color:#ffffff;width:100%;font-family:consolas,&#39;font-size:12px;margin:0;">...
</pre>
<pre style="background-color:#ffffff;width:100%;font-family:consolas,&#39;font-size:12px;margin:0;">$this-&#62;User-&#62;find('<span style="color:#8b0000;">all</span>');
</pre>
<pre style="background-color:#ffffff;width:100%;font-family:consolas,&#39;font-size:12px;margin:0;">...
</pre>
<pre style="background-color:#ffffff;width:100%;font-family:consolas,&#39;font-size:12px;margin:0;"><span style="color:#0000ff;">?&#62;</span></pre>
</pre>
<p>&#160;</p>
<p>будет эквивалентно</p>
<pre>
<pre style="background-color:#ffffff;width:100%;font-family:consolas,&#39;font-size:12px;margin:0;"><span style="color:#0000ff;">&#60;?</span>php
</pre>
<pre style="background-color:#ffffff;width:100%;font-family:consolas,&#39;font-size:12px;margin:0;">...
</pre>
<pre style="background-color:#ffffff;width:100%;font-family:consolas,&#39;font-size:12px;margin:0;">$this-&#62;User-&#62;find('<span style="color:#8b0000;">all</span>', <a style="color:#ffa500;" href="http://www.php.net/array">array</a>(
</pre>
<pre style="background-color:#ffffff;width:100%;font-family:consolas,&#39;font-size:12px;margin:0;">    '<span style="color:#8b0000;">conditions</span>' =&#62; <a style="color:#ffa500;" href="http://www.php.net/array">array</a>(
</pre>
<pre style="background-color:#ffffff;width:100%;font-family:consolas,&#39;font-size:12px;margin:0;">        '<span style="color:#8b0000;">User.site_id</span>' =&#62; SITE_ID,
</pre>
<pre style="background-color:#ffffff;width:100%;font-family:consolas,&#39;font-size:12px;margin:0;">    )
</pre>
<pre style="background-color:#ffffff;width:100%;font-family:consolas,&#39;font-size:12px;margin:0;">);
</pre>
<pre style="background-color:#ffffff;width:100%;font-family:consolas,&#39;font-size:12px;margin:0;">...
</pre>
<pre style="background-color:#ffffff;width:100%;font-family:consolas,&#39;font-size:12px;margin:0;"><span style="color:#0000ff;">?&#62;</span></pre>
</pre>
<p>&#160;</p>
<p>Пользоваться, конечно, следует с осторожностью, так как некоторые операции, например updateAll и deleteAll c $cascade=false работают напрямую с источником данных и behavior остается не у дел (deleteAll c $cascade=true будет работать как и ожидается, с подстановкой параметров).</p>
<p>Исходный код лежит на гитхабе &#8211; <a href="http://github.com/evilbloodydemon/cakephp-scope">http://github.com/evilbloodydemon/cakephp-scope</a></p>
<p>Замечания и предложения приветствуются.</p>
</div>]]></content:encoded>
</item>
<item>
<title><![CDATA[CakePHP and jQuery FullCalendar plugin (Part III – gotoDate method)]]></title>
<link>http://stripesblueandgreen.wordpress.com/2009/11/15/cakephp-and-jquery-fullcalendar-plugin-part-iii-%e2%80%93-gotodate-method/</link>
<pubDate>Sun, 15 Nov 2009 02:44:16 +0000</pubDate>
<dc:creator>stripesblueandgreen</dc:creator>
<guid>http://stripesblueandgreen.wordpress.com/2009/11/15/cakephp-and-jquery-fullcalendar-plugin-part-iii-%e2%80%93-gotodate-method/</guid>
<description><![CDATA[One thing that is essential in having a calendar for a web application is the capability to have a g]]></description>
<content:encoded><![CDATA[<div class='snap_preview'><p>One thing that is essential in having a calendar for a web application is the capability to have a go to date that will enable a user to go directly and display a specific date. On the <a href="http://arshaw.com/fullcalendar/">FullCalendar</a> plugin, I made use of the gotoDate method. It is not complicated, you just have to create a form that will ask a user to input the desired date to view, and a javascript function that will trigger the gotoDate method.</p>
<p>Note: I advise you to read my previous post (<a href="http://stripesblueandgreen.wordpress.com/2009/11/15/cakephp-and-jquery-fullcalendar-plugin-part-i-retrieve-events-from-database/"> CakePHP and jQuery FullCalendar plugin (Part I – Retrieve events from database)</a>) first regarding this plugin. </p>
<p>Add this to your index page where the calendar is displayed. (ie. app/views/calendar/index.ctp)</p>
<pre>

&#60;script type='text/javascript'&#62;

function gotodate(userdate){

var dateinput = new Date(userdate); // userdate is what the user has inputted.

$('#calendar')
     	.fullCalendar('changeView', 'basicDay')  // we called the changeView method to display basicDay view.
     	.fullCalendar('gotoDate', dateinput);  // here's where we call the gotoDate method to do the magic.

}

&#60;/script&#62;
</pre>
<p>Hope this helps! If you have any suggestions or corrections feel free to do so <img src='http://s.wordpress.com/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' />  By the way, you could also check out <a href="http://stripesblueandgreen.wordpress.com/2009/11/15/cakephp-and-jquery-fullcalendar-plugin-part-i-retrieve-events-from-database/">Part I &#8211; Retrieve from database</a>  and <a href="http://stripesblueandgreen.wordpress.com/2009/11/15/cakephp-and-jquery-fullcalendar-plugin-part-ii-%E2%80%93-editable-feature/">Part II &#8211; Editable feature</a> <img src='http://s.wordpress.com/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </p>
</div>]]></content:encoded>
</item>
<item>
<title><![CDATA[CakePHP and jQuery FullCalendar plugin (Part II – Editable feature)]]></title>
<link>http://stripesblueandgreen.wordpress.com/2009/11/15/cakephp-and-jquery-fullcalendar-plugin-part-ii-%e2%80%93-editable-feature/</link>
<pubDate>Sun, 15 Nov 2009 01:55:54 +0000</pubDate>
<dc:creator>stripesblueandgreen</dc:creator>
<guid>http://stripesblueandgreen.wordpress.com/2009/11/15/cakephp-and-jquery-fullcalendar-plugin-part-ii-%e2%80%93-editable-feature/</guid>
<description><![CDATA[FullCalendar plugin has an editable feature that makes it possible to update events by dragging and ]]></description>
<content:encoded><![CDATA[<div class='snap_preview'><p><a href="http://arshaw.com/fullcalendar/">FullCalendar</a> plugin has an editable feature that makes it possible to update events by dragging and dropping posts anywhere within the calendar. This time, I&#8217;ll be sharing on how I&#8217;ve utilized this feature, as well as on how to update the events on the database. </p>
<p>Note: I advise you to read my previous post (<a href="http://stripesblueandgreen.wordpress.com/2009/11/15/cakephp-and-jquery-fullcalendar-plugin-part-i-retrieve-events-from-database/"> CakePHP and jQuery FullCalendar plugin (Part I – Retrieve events from database)</a>) first regarding this plugin. </p>
<p>So let&#8217;s begin!</p>
<p>Add this to your index page where the calendar is displayed. (ie. app/views/calendar/index.ctp)</p>
<pre>

// include this in the FullCalendar script...

editable: true,

eventDrop: function(event) {	// Make sure to read the plugin's documentation <img src='http://s.wordpress.com/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> 

var dt = new Date(event.start);   // event.start is the new date where you dragged and dropped the event post.
var yr = dt.getFullYear();
var dy = dt.getDate();
var mth = dt.getMonth()+1;
var hrs = dt.getHours();
var mns = dt.getMinutes();

var newdate = yr+'-'+mth+'-'+dy;  // pass this date to the database via post.

$.post("http://www.yoursite.com/calendar/edit/id:"+event.id+"/date:"+newdate, function(data){});

} 
</pre>
<p>On your controller (ie. app/controllers/calendar_controller.php), create the edit function.</p>
<pre>

function edit($id=null){

$this-&#62;Event-&#62;id = $this-&#62;params['named']['id'];
 // By the way I made use of the params to get the values.
$this-&#62;Event-&#62;saveField('event_date',$this-&#62;params['named']['date']);

}
</pre>
<p>So that&#8217;s about it. <img src='http://s.wordpress.com/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' />  You can also use the eventResize: function(), this feature will let you resize or extend the date duration of an event. </p>
<p>Also check out <a href="http://stripesblueandgreen.wordpress.com/2009/11/15/cakephp-and-jquery-fullcalendar-plugin-part-i-retrieve-events-from-database/">Part I &#8211; Retrieve from database</a>  and <a href="http://stripesblueandgreen.wordpress.com/2009/11/15/cakephp-and-jquery-fullcalendar-plugin-part-iii-%E2%80%93-gotodate-method/">Part III gotoDate method</a> <img src='http://s.wordpress.com/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </p>
</div>]]></content:encoded>
</item>
<item>
<title><![CDATA[CakePHP and jQuery FullCalendar plugin (Part I - Retrieve events from database)]]></title>
<link>http://stripesblueandgreen.wordpress.com/2009/11/15/cakephp-and-jquery-fullcalendar-plugin-part-i-retrieve-events-from-database/</link>
<pubDate>Sun, 15 Nov 2009 01:41:42 +0000</pubDate>
<dc:creator>stripesblueandgreen</dc:creator>
<guid>http://stripesblueandgreen.wordpress.com/2009/11/15/cakephp-and-jquery-fullcalendar-plugin-part-i-retrieve-events-from-database/</guid>
<description><![CDATA[This week I&#8217;ve incorporated the jQuery&#8217;s FullCalendar plugin to the project I&#8217;m wo]]></description>
<content:encoded><![CDATA[<div class='snap_preview'><p>This week I&#8217;ve incorporated the jQuery&#8217;s FullCalendar plugin to the project I&#8217;m working. It was a bit challenging task but really glad to make it worked. <img src='http://s.wordpress.com/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' />  I hope to help someone and share what I did to make this task possible.</p>
<p>First, I assume that you have already checked out the <a href="http://arshaw.com/fullcalendar/">FullCalendar </a> demo and downloaded the source code. You&#8217;re now in the process of incorporating it to your web application. </p>
<p>So to get things started, you need to include the <a href="http://www.jquery.com">jQuery</a> script and <a href="http://arshaw.com/fullcalendar/">FullCalendar</a> script plus css in your default layout page. (ie. app/views/layout/default.ctp)</p>
<pre>
&#60;?php echo $javascript-&#62;link('jquery-1.3.2'); ?&#62;
&#60;?php echo $javascript-&#62;link('fullcalendar.min'); ?&#62;

// jquery ui purpose for this has something to do with the editing part of the FullCalendar plugin

&#60;?php echo $javascript-&#62;link('ui.core'); ?&#62;
&#60;?php echo $javascript-&#62;link('ui.draggable'); ?&#62;
&#60;?php echo $javascript-&#62;link('ui.resizable'); ?&#62;

&#60;?php echo $html-&#62;css('fullcalendar'); ?&#62; 
</pre>
<p>On your controller, let&#8217;s create the code that will retrieve calendar events from the database. (ie. app/controllers/calendar_controller.php)</p>
<pre>

function index() {

// get all the events from the database.
$events = $this-&#62;Event-&#62;find('all');

// insert rows to an array.
for ($a=0; count($events)&#62; $a; $a++){

$rows[]= '{"id":'.$events[$a]['Event']['id'].', "title":"'.events[$a]['Event']['name'].'", "start":"'.$events[$a]['Event']['event_date'].'", "className":"'.$events[$a]['Event']['type'].'","type":"'.$events[$a]['Event']['type'].'"}';

}

// convert the array to a string.
if ($rows){
$convertojson = implode(",", $rows);
}

// pass the string to the json variable. this will then be passed  and printed to the javascript code.
$this-&#62;set('json',"[".$convertojson."]"); 

}
</pre>
<p>On your views add the index page for displaying the calendar. (ie. app/views/calendar/index.ctp )</p>
<pre>

&#60;script type='text/javascript'&#62;

$(document).ready(function() {

$('#calendar').fullCalendar({

	header: {
		left: 'prev,next today',
		center: 'title',
		right: 'month,agendaWeek,agendaDay'
		},
	events: &#60;?php echo $json; ?&#62; // this is where we call the php variable

});
)};
&#60;/script&#62;

&#60;div id='calendar' style='width: 900px; margin: 0 auto;'&#62;&#60;/div&#62;
</pre>
<p>So that&#8217;s it! You could also check out <a href="http://stripesblueandgreen.wordpress.com/2009/11/15/cakephp-and-jquery-fullcalendar-plugin-part-ii-%E2%80%93-editable-feature/">Part II &#8211; Editable feature</a>  and <a href="http://stripesblueandgreen.wordpress.com/2009/11/15/cakephp-and-jquery-fullcalendar-plugin-part-iii-%E2%80%93-gotodate-method/">Part III gotoDate method</a> <img src='http://s.wordpress.com/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </p>
</div>]]></content:encoded>
</item>
<item>
<title><![CDATA[Zend Framework vs CakePHP]]></title>
<link>http://aousmer.wordpress.com/2009/11/13/zend-framework-vs-cakephp/</link>
<pubDate>Fri, 13 Nov 2009 19:01:18 +0000</pubDate>
<dc:creator>Abdellah Ousmer</dc:creator>
<guid>http://aousmer.wordpress.com/2009/11/13/zend-framework-vs-cakephp/</guid>
<description><![CDATA[Durant mon passage en tant que développeur dans une agence multimedia dans le cadre de mon stage de ]]></description>
<content:encoded><![CDATA[<div class='snap_preview'><p style="text-align:center;"><img class="size-full wp-image-46 alignnone" title="cakzendphp1" src="http://aousmer.wordpress.com/files/2009/11/cakzendphp1.jpg" alt="cakzendphp1" width="108" height="99" /> <img class="size-full wp-image-44 alignnone" title="cakphp" src="http://aousmer.wordpress.com/files/2009/11/cakphp.jpg" alt="cakphp" width="108" height="99" /></p>
<p>Durant mon <img src="/Users/bello/Pictures/cakzendphp.jpg" alt="" />passage en tant que développeur dans une agence multimedia d<img src="/Users/bello/AppData/Local/Temp/moz-screenshot-1.jpg" alt="" />ans le cadre de mon stage de fin d&#8217;étude, j&#8217;ai pu acquérir des connaissances et surtout j&#8217;ai pu apprendre à utiliser un nouvel outil(Et oui!! nouveau pour moi^^) le <a href="http://framework.zend.com/" target="_blank">Zend framework</a> mais y a aussi CakePHP qui utilise encore PHP 4. bon j&#8217;aime pas trop parler, je vous laisse voir ce comparatif qui est très instructif. Bonne lecture;))<a title="ZendvsCake" href="http://g-rossolini.developpez.com/comparatifs/php/cake-zf/" target="_self"><strong><span style="color:#339966;"><em>&#62;</em></span><span style="color:#339966;"><em>COMPARATIF</em></span></strong></a></p>
<p><img src="/Users/bello/AppData/Local/Temp/moz-screenshot-3.jpg" alt="" /></p>
<div id="_mcePaste" style="overflow:hidden;position:absolute;left:-10000px;top:0;width:1px;height:1px;"><img src="/Users/bello/Pictures/cakzendphp.jpg" alt="" /></div>
</div>]]></content:encoded>
</item>
<item>
<title><![CDATA[Installing CakePHP Framework on Windows]]></title>
<link>http://prabhulsankar.wordpress.com/2009/11/11/installing-cakephp-framework-on-windows/</link>
<pubDate>Wed, 11 Nov 2009 12:11:52 +0000</pubDate>
<dc:creator>prabhulsankar</dc:creator>
<guid>http://prabhulsankar.wordpress.com/2009/11/11/installing-cakephp-framework-on-windows/</guid>
<description><![CDATA[Following is a good intro on installing and setting up CakePHP Framework in Windows environment.]]></description>
<content:encoded><![CDATA[<div class='snap_preview'><p>Following is a good intro on installing and setting up <a title="CakePHP Framework" href="http://cakephp.org/" target="_blank">CakePHP </a>Framework in Windows environment.</p>
<p style="text-align:center;"><span style='text-align:center; display: block;'><object width='425' height='350'><param name='movie' value='http://www.youtube.com/v/fMsmPa7Tm-o&#038;rel=1&#038;fs=1&#038;showsearch=0&#038;hd=0' /><param name='allowfullscreen' value='true' /><param name='wmode' value='transparent' /><embed src='http://www.youtube.com/v/fMsmPa7Tm-o&#038;rel=1&#038;fs=1&#038;showsearch=0&#038;hd=0' type='application/x-shockwave-flash' allowfullscreen='true' width='425' height='350' wmode='transparent'></embed></object></span></p>
</div>]]></content:encoded>
</item>
<item>
<title><![CDATA[ACLに挑戦。]]></title>
<link>http://yashio.wordpress.com/2009/11/10/acl%e3%81%ab%e6%8c%91%e6%88%a6%e3%80%82/</link>
<pubDate>Tue, 10 Nov 2009 14:39:58 +0000</pubDate>
<dc:creator>yashio</dc:creator>
<guid>http://yashio.wordpress.com/2009/11/10/acl%e3%81%ab%e6%8c%91%e6%88%a6%e3%80%82/</guid>
<description><![CDATA[ACLを早急にしらないといけない、ってことで必死に情報収集。で、わからないながらも手を動かさないと始まらない。ってことで ・情報をさがす ・一番簡単そうにやってるところをみつけて、まずそれをやってみる]]></description>
<content:encoded><![CDATA[<div class='snap_preview'><p>ACLを早急にしらないといけない、ってことで必死に情報収集。で、わからないながらも手を動かさないと始まらない。ってことで<br />
・情報をさがす<br />
・一番簡単そうにやってるところをみつけて、まずそれをやってみる<br />
・動いてから、中身をみる…</p>
<p>というグダグダな展開、でもやらないと「これだめじゃーん」なのか「結構つかえる」なのかわかんないので。<br />
まずは参考サイト。<a href="http://d.hatena.ne.jp/slywalker/20080702/1215011594">こちら</a>です。まずこちらを１０回くらいよんでみた…。そしてそのとおりにやってみることにします。</p>
<p>・んもう、書いてあるとおり！書いてあるとおりにとりあえずやってみる。<br />
というのを実践してみた。「えー動かなかったらどうしよう」とかいろいろありましたけど、まず最後までやってみよう。これって結構大事ですよね。私みたいなタイプは「…難しいなあ、できるかなあ」って考える時間が長いのです。「グダグダいわずにやれ！手をうごかせ！」っていうのが大事なので、やってみます。</p>
<p>・テーブル＆モデルの作成（ユーザ、グループ）<br />
・コントローラーの作成（ACLの読み込み）<br />
・ビューのページ作成<br />
・グループ作成<br />
・ユーザ作成<br />
ここまでは順調。<br />
…さてここです。コンソール。コンソールだよねやっぱ。これだよこれが全部悪いの＞＜<br />
でももうやります、やらせていただきますっ！<br />
上記作業の後、コマンドプロンプトで、<br />
xampp\htdocs\cake\cake\console上で</p>
<p>「cake acl initdb」<br />
って打ちましたら、Your database configuration was not found. Take a moment to create one.<br />
「はい…？」<br />
ええと、私だけかもしれませんが設定ファイルを読み込んでくれないのですね。現在私はVM環境で構築したCentOS上のデータベースを参照して開発をしているため、ローカルにあるcakephpの設定ファイルはVM上のｍｙｓｑｌを参照するように設定されています。多分だけど…。ただ上記のコマンドをうっただけだとローカルのデータベースに対して「何か」をしようとしてるんじゃないかな、と思ったので。<br />
<a href="http://casey.jp/article.php?story=20090929020508726">こちら</a>を参考に、現在のローカルにある設定ファイル（VM上のデータベース情報）をみるように、app配下の設定ファイルをみるように指定します。上記URLのように。</p>
<p>%php /home/[SakuraAccount]/cake125/cake/console/cake.php -app /home/[SakuraAccount]/www/foo.bar.com/app/ acl initdb</p>
<p>私はWindows環境で上記を行ったので若干書き方は違いますが、/home/[SakuraAccount]/www/foo.bar.com/app/ここまでが設定ファイルのある場所を指定しています。昨日、自宅でこれをやったらできたんだけど、今日職場のXampp環境でやったら（パス設定は同じ）ちょっと違ったのか、cakeコマンドは実行できないだのphpコマンドは実行できないだのガタガタいわれました。んもーパス通すとか、全然やってない。<br />
・xampp\phpにパスを通す<br />
・xampp\htdocs\cake\cake\consoleにパスを通す<br />
ことで<br />
＞cake -app [appまでのパス] acl initdb<br />
で無事ACL関係のテーブルが作成されました。あーここを解消したURLをブックマークするのをわすれてたか。</p>
<p>先ほどの<a href="http://d.hatena.ne.jp/slywalker/20080702/1215011594">こちら</a>のサイトをすべて「順番とおり」にやれば、できます。順番まちがえるといろいろ面倒なので順番は守ったほうが良いｗ私はこの後、<br />
cake acl grant User.1 Users/view all<br />
なんかを追加して管理権限を有するユーザでログインし、ユーザの表示ができていることを確かめました。<br />
結論からいうと（まだ結論まで達してないが）<br />
やってしまえば簡単。っていうか実際の権限管理のテーブルも同じような構成のテーブルを作ることになる。<br />
initdbコマンドは実はテーブルを作るだけのスクリプトのようで、動かなかったらphpmyadminで作ればいいだけ。</p>
<p>ここまではいいんだけど、実際、データを入れるところで、当然なんですけどデータをいれるのもコマンドなんですね。<br />
これもいいんだけど、これはちょっと正直微妙だなあ。<br />
特定のコントローラー/アクション　をグループやユーザーに対して付与するわけなんだけど、このデータを作成する、っていう手順のコマンド操作はちょっと微妙かも。たとえば、パッケージで社内で使う社内ウェブサーバで動作するアプリとして売り出すものを作った場合には<br />
この処理をパッケージを買った人にしてもらうか、自動的に作成するスクリプトを作る必要がある。</p>
<p>それと重要なことをわすれていたのだけど、ACLでカバーするのはいわゆる縦の「機能」に関連したルールということ。今回私が目指しているのは当然、その機能もほしいんだけど、もう一つは横（データの違い）でも権限を設定しないといけないということ。<br />
同じユーザーでも、Aというデータについては参照を許可し、Bというデータについては参照と編集を許可する、というもの。いまのところ、ACLの機能でこの横のデータについての権限を設定できる要素はないみたい（そりゃカスタマイズすればできると思うけどさー）ということでちょっと保留。でも権限設定についてはACL、それほど難しくないんじゃない？という印象。<br />
（生成されるテーブルもacosとかarosとか、しょうがないのかなあ、cakephpのネーミングルールにあわせたものとかにしたほうがいいんじゃないのか？って気がしましたｗ。システムで使用するからわざとこういうネーミング？なのかなあ）</p>
<p>今回、cakematsuriでACLが話題になって、「結構使ってない」「わかりずらい」っていううわさがあったし、実際使用してるひとも少なかった。cakematsuriが今回ACLをやってみるべ！と私の背中を押してくれたと思います。もっとじっくり勉強して自分でカスタマイズできたらいいかな、という気持ちもありますが、現状の業務との兼ね合いがあるから難しいなあー。上記SLYWALKERさんのサイトは続きがあって、初期化するコンポーネントもあるので、そちらも時間があるときに挑戦してみようかなあ、と思っています。<br />
先人のブログ記事に毎回助けられております。感謝感謝。ほんと、今の時代に生まれててよかったよ…。内部的なもうちょっと深いところを今後もうちょっと情報収集できたらいいかなあ、と思っていますが、いつになるかなあ・・・。</p>
<p>しかし、Authcompornent,ACLと一応斜め読みして実際に動かしてみました。あとは…なんだろうな。楽しいけどネ！</p>
<p>※11月12日追記。パスの設定をメモしてたところがわからなかったので上記に追記。<br />
cakeコマンドとphpコマンドが実行できないので、暫定的に設定する(windowsVista,xampp環境での例）。<br />
C:\xampp\php &#62;SET PATH=%PATH%;%CD%<br />
C:\&#8230;\console &#62;SET PATH=%PATH%;%CD%</p>
</div>]]></content:encoded>
</item>
<item>
<title><![CDATA[How to set a default value for &lt;select&gt; with CakePHP]]></title>
<link>http://alphaquality.wordpress.com/2009/11/09/how-to-set-a-default-value-for-select-with-cakephp/</link>
<pubDate>Mon, 09 Nov 2009 18:40:19 +0000</pubDate>
<dc:creator>maxmight</dc:creator>
<guid>http://alphaquality.wordpress.com/2009/11/09/how-to-set-a-default-value-for-select-with-cakephp/</guid>
<description><![CDATA[Sometimes things that are simple in HTML/PHP are really well hidden in CakePHP. Things like setting ]]></description>
<content:encoded><![CDATA[<div class='snap_preview'><p>Sometimes things that are simple in HTML/PHP are really well hidden in CakePHP. Things like setting a default value for &#60;select&#62;. Let&#8217;s say that we have the following field in our view:</p>
<pre class="brush: php;">
echo $form-&#62;input('field', array('type' =&#62; 'select', 'options' =&#62; $field_options));
</pre>
<p>$field_options is an array which contains values for the combo. At first I thought that this array is the place to provide a default value for it but as it turned out I was wrong. The right way is:</p>
<pre class="brush: php;">
$this-&#62;data['Model']['field'] = &#34;some_value&#34;;
</pre>
<p>So if we have a &#8220;some_value&#8221; in our $field_options array it will be selected.<br />
I hope someone will find this helpful <img src='http://s.wordpress.com/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </p>
</div>]]></content:encoded>
</item>
<item>
<title><![CDATA[Click the buttons, I tell ya...]]></title>
<link>http://teknoid.wordpress.com/2009/11/08/click-the-buttons-i-tell-ya/</link>
<pubDate>Sun, 08 Nov 2009 13:38:05 +0000</pubDate>
<dc:creator>teknoid</dc:creator>
<guid>http://teknoid.wordpress.com/2009/11/08/click-the-buttons-i-tell-ya/</guid>
<description><![CDATA[View This Pollsurvey software]]></description>
<content:encoded><![CDATA[<div class='snap_preview'><a name="pd_a_2225875"></a><div class="PDS_Poll" id="PDI_container2225875" style="display:inline-block;"></div><script type="text/javascript" language="javascript" charset="utf-8" src="http://static.polldaddy.com/p/2225875.js"></script>
		<noscript>
		<a href="http://answers.polldaddy.com/poll/2225875/">View This Poll</a><br/><span style="font-size:10px;"><a href="http://www.polldaddy.com">survey software</a></span>
		</noscript>
</div>]]></content:encoded>
</item>
<item>
<title><![CDATA[Zend Framework Gdata API and Cakephp insert a new row to Google spreadsheet]]></title>
<link>http://adrenalinexp.wordpress.com/2009/11/07/zend-framework-gdata-api-and-cakephp-insert-a-new-row-to-google-spreadsheet/</link>
<pubDate>Sat, 07 Nov 2009 21:54:03 +0000</pubDate>
<dc:creator>Adrenalin</dc:creator>
<guid>http://adrenalinexp.wordpress.com/2009/11/07/zend-framework-gdata-api-and-cakephp-insert-a-new-row-to-google-spreadsheet/</guid>
<description><![CDATA[To setup Zend Framework Gdata, see this post on Using the Zend Framework in CakePHP , this helped to]]></description>
<content:encoded><![CDATA[<div class='snap_preview'><p>To setup Zend Framework Gdata, see this post on <a href="http://britg.com/2008/07/07/using-the-zend-framework-in-cakephp/">Using the Zend Framework in CakePHP </a>, <a href="http://techmike.wordpress.com/2009/07/03/zend-framework-gdata-in-cakephp-contacts-api/">this</a> helped too.</p>
<p>As reference use: <a href="http://code.google.com/apis/spreadsheets/data/1.0/developers_guide_php.html">Google Spreadsheets APIs and Tools Developer&#8217;s Guide: PHP</a><br />
In this doc you will see functions like printFeed, that can be found in <a href="http://framework.zend.com/svn/framework/standard/trunk/demos/Zend/Gdata/Spreadsheet-ClientLogin.php">Spreadsheet-ClientLogin.php</a> it&#8217;s a SimpleCRUD implementation for google spreadsheet.</p>
<p>The document key is http://spreadsheets.google.com/ccc?key=<strong>HERE</strong>&#38;hl=en, you will need it to point to the spreadsheet you want to edit.<br />
Also spreadsheets can have multiple worksheets, you will need the key of the worksheet you want to edit, this key can be get by calling the promptForWorksheet() function.<br />
Also, when adding a new row, you need to give a list of header-row=&#62;value, so the tricky part here is to get the &#8220;header-row&#8221;. The <a href="http://code.google.com/apis/spreadsheets/data/1.0/developers_guide_php.html#listFeedExample">documentation</a> describe it as:<br />
&#8220;the first row of the worksheet as a header row&#8221;<br />
&#8220;column headers will be converted into valid XML namespaces&#8221;<br />
I did just listGetAction() and look up the names of the header-row to use.</p>
<p>So here is the code, hopefully this will give you a fast start and save you time.</p>
<pre class="brush: php;">
class SomeController extends AppController {
var $uses = null; // Don't use any model
function index() {
	App::import('Vendor', 'zend_include_path');
	App::import('Vendor', 'Zend_Gdata', true, false, 'Zend/Gdata.php');

	Zend_Loader::loadClass('Zend_Http_Client');
	Zend_Loader::loadClass('Zend_Gdata');
	Zend_Loader::loadClass('Zend_Gdata_ClientLogin');
	Zend_Loader::loadClass('Zend_Gdata_Spreadsheets');

	$authService = Zend_Gdata_Spreadsheets::AUTH_SERVICE_NAME;
	$user = 'username';
	$pass = 'password';
	$this-&#62;currKey = 'thesheetkey';

	try {
		$httpClient = Zend_Gdata_ClientLogin::getHttpClient($user, $pass, $authService);
		$this-&#62;gdClient = new Zend_Gdata_Spreadsheets($httpClient);

		$this-&#62;promptForWorksheet(0); // Put the 0th worksheet of our sheet to $this-&#62;currWkshtId
		$this-&#62;listGetAction(); // Will list all the rows inside the worksheet

		$row = array('column1'=&#62;'value','column2'=&#62;'value','columnN'=&#62;'value');
		$this-&#62;listInsertAction($row);
		} catch ( Exception $e )  {
		echo $e-&#62;getMessage();
	}
}

public function promptForWorksheet($wordSheetI=0)
{
	$query = new Zend_Gdata_Spreadsheets_DocumentQuery();
	$query-&#62;setSpreadsheetKey($this-&#62;currKey);
	$feed = $this-&#62;gdClient-&#62;getWorksheetFeed($query);
	print &#34;== Available Worksheets ==\n&#34;;
	$this-&#62;printFeed($feed);
	$input = $wordSheetI;
	$currWkshtId = split('/', $feed-&#62;entries[$input]-&#62;id-&#62;text);
	$this-&#62;currWkshtId = $currWkshtId[8];
}
public function listGetAction()
{
	$query = new Zend_Gdata_Spreadsheets_ListQuery();
	$query-&#62;setSpreadsheetKey($this-&#62;currKey);
	$query-&#62;setWorksheetId($this-&#62;currWkshtId);
	$this-&#62;listFeed = $this-&#62;gdClient-&#62;getListFeed($query);
	print &#34;entry id &#124; row-content in column A &#124; column-header: cell-content\n&#34;.
	&#34;Please note: The 'dump' command on the list feed only dumps data until the first blank row is encountered.\n\n&#34;;

	$this-&#62;printFeed($this-&#62;listFeed);
	print &#34;\n&#34;;
}
public function printFeed($feed)
{
	$i = 0;
	foreach($feed-&#62;entries as $entry) {
		if ($entry instanceof Zend_Gdata_Spreadsheets_CellEntry) {
			print $entry-&#62;title-&#62;text .' '. $entry-&#62;content-&#62;text . &#34;\n&#34;;
			} else if ($entry instanceof Zend_Gdata_Spreadsheets_ListEntry) {
			print $i .' '. $entry-&#62;title-&#62;text .' &#124; '. $entry-&#62;content-&#62;text . &#34;\n&#34;;
			} else {
			print $i .' '. $entry-&#62;title-&#62;text . &#34;\n&#34;;
		}
		$i++;
	}
}
public function listInsertAction($rowArray)
{
	//$rowArray = $this-&#62;stringToArray($rowData);
	$entry = $this-&#62;gdClient-&#62;insertRow($rowArray, $this-&#62;currKey,
	$this-&#62;currWkshtId);

	if ($entry instanceof Zend_Gdata_Spreadsheets_ListEntry) {
		foreach ($rowArray as $column_header =&#62; $value) {
			echo &#34;Success! Inserted '$value' in column '$column_header' at row &#34;.
			substr($entry-&#62;getTitle()-&#62;getText(), 5) .&#34;\n&#34;;
		}
	}
}
}
</pre>
<p>The same code in the pastebin http://pastebin.com/f12021eb.</p>
</div>]]></content:encoded>
</item>
<item>
<title><![CDATA[debug kit を導入しよう。]]></title>
<link>http://yashio.wordpress.com/2009/11/08/debug-kit-%e3%82%92%e5%b0%8e%e5%85%a5%e3%81%97%e3%82%88%e3%81%86%e3%80%82/</link>
<pubDate>Sat, 07 Nov 2009 15:03:24 +0000</pubDate>
<dc:creator>yashio</dc:creator>
<guid>http://yashio.wordpress.com/2009/11/08/debug-kit-%e3%82%92%e5%b0%8e%e5%85%a5%e3%81%97%e3%82%88%e3%81%86%e3%80%82/</guid>
<description><![CDATA[今日ガイドブック1.2を見てたら、debug kitの紹介があって、cakematsuriでも「pluginっていえばdebug kitですよね」的な話がでてて、「えーなんか難しそうだな。」って思って]]></description>
<content:encoded><![CDATA[<div class='snap_preview'><p>今日ガイドブック1.2を見てたら、debug kitの紹介があって、cakematsuriでも「pluginっていえばdebug kitですよね」的な話がでてて、「えーなんか難しそうだな。」って思ってたんだけど、ガイドブックにすごく簡単にかいてあったので、こりゃいれてみよう。と思いいれてみることに。</p>
<p>参考にしたページは<a href="http://www.syuhari.jp/blog/archives/1641">こちら</a>です。matsuriでも、ご本人とお話させていただきました。大変きさくな方でした。まずは<a href="http://www.ohloh.net/p/cakephp-debugkit/">こちら</a>の1.1バージョンをダウンロードし、解凍してpluginフォルダにぶっこみ。<br />
app/app_controller.phpに</p>
<pre class="brush: php;">
	public $components = array('Auth','DebugKit.Toolbar');
</pre>
<p>とDebugKit.Toolbarを入れました。Auth使ってるから後にくっつけた。ちなみにpluginをいれていないとAuthも動かないのでフォルダにいれてから書こう。<br />
いれたけど、動かないよ！あれれ？…。<br />
あ、これこれ。<br />
<strong>※だいじなことその１　Config の debug の値を 1 以上だよ！</strong><br />
おｋおｋ、やろうじゃないか。ってことでやってみた。そしたら…。<br />
レベルを１にしたらいまさらな「securty.saltの値をかえてよね！」ってメッセージが…あれこれ変えてなかったの…あ、っそう…。<br />
ってことで変更。そしたら結構noticeがでてきたよー。あれま。ちょろちょろ変更してみる。<br />
で、画面右上をみると動いてるよ！すごいよ！ケーキマークをクリックするといろいろログでるよ。すごいや！<br />
で、もって、ガチャガチャ動かしてみると、画面によってケーキマークがでないところが&#8230;。なんで？<br />
また<a href="http://www.syuhari.jp/blog/archives/1641">こちら</a>を確認<br />
<strong>※だいじたなことその２　Scaffoldではうごかないらしい</strong><br />
なるほどね。まあそうかもな…と納得（いらない、ということかなあ）。<br />
これでデバッグがだいぶ楽になりますね。会社の開発環境にもいれよう。こりゃいれない理由がないや。</p>
<p>ただ、これ結構速度に関係しますね。わりともっさりする。本番では使わないのでいいんだけど。<br />
かかった時間とかもわかるので今後、実際の開発で絶対に使えそう。<br />
pluginも使ってみると、やっぱり自作でもりもりつくるよりも（もちろん、ドキュメントをきちんとみて知ることが大事だけど）、<br />
あるものを使う、と途端に生産性がかわってくるなーと。<br />
作りこむことは大事だけど、業務に特化した箇所の作りこみに注力したほうがいいかな、と。<br />
デザインも、ある程度こちらで思案していかないといけないしね…。</p>
<p>ログインに関しては、AuthCompornentを使うことに。あわせて入力のチェックは追加していく予定だけど。<br />
これから、ACLを読み解いていこうと思っています。AuthCompornent + ACLでクリアできればベスト。<br />
ちなみに、ガイドブック1.2を見ながら自分の自宅マシンで作成してたウェブサービスがあったのですが、これもAuthcompornent<br />
に変更しました。超<a href="http://umakoya.com/blog/log/eid508.html">ここ</a>が参考になりました。<br />
それも後々、記事にまとめたいと思います。</p>
<p>少しずつ、技術的なtipsが自分のブログに蓄積するといいなあ、と思いつつ。</p>
</div>]]></content:encoded>
</item>
<item>
<title><![CDATA[Идеальная админка сайта!]]></title>
<link>http://paganez.wordpress.com/2009/11/07/%d0%b8%d0%b4%d0%b5%d0%b0%d0%bb%d1%8c%d0%bd%d0%b0%d1%8f-%d0%b0%d0%b4%d0%bc%d0%b8%d0%bd%d0%ba%d0%b0-%d1%81%d0%b0%d0%b9%d1%82%d0%b0/</link>
<pubDate>Sat, 07 Nov 2009 14:45:12 +0000</pubDate>
<dc:creator>paganez</dc:creator>
<guid>http://paganez.wordpress.com/2009/11/07/%d0%b8%d0%b4%d0%b5%d0%b0%d0%bb%d1%8c%d0%bd%d0%b0%d1%8f-%d0%b0%d0%b4%d0%bc%d0%b8%d0%bd%d0%ba%d0%b0-%d1%81%d0%b0%d0%b9%d1%82%d0%b0/</guid>
<description><![CDATA[IB.Pro CMS Ну вот и она&#8230; Идеальная на мой взгляд! Это была середина дня. 7 ноября. Я подбирал ]]></description>
<content:encoded><![CDATA[IB.Pro CMS Ну вот и она&#8230; Идеальная на мой взгляд! Это была середина дня. 7 ноября. Я подбирал ]]></content:encoded>
</item>
<item>
<title><![CDATA[續 Security Component]]></title>
<link>http://mooncakephp.wordpress.com/2009/11/06/%e7%ba%8c-security-component/</link>
<pubDate>Fri, 06 Nov 2009 17:09:00 +0000</pubDate>
<dc:creator>joetsuihk</dc:creator>
<guid>http://mooncakephp.wordpress.com/2009/11/06/%e7%ba%8c-security-component/</guid>
<description><![CDATA[Security Component enable 了以後, 在 $form-&gt;end() 的時候會加一個 hash token. 這很容易理解, 就是用這個hash tag 證明這張表單的正確]]></description>
<content:encoded><![CDATA[<div class='snap_preview'><p>Security Component enable 了以後, 在 $form-&#62;end() 的時候會加一個 hash token. 這很容易理解, 就是用這個hash tag 證明這張表單的正確性. 但實際上這個hash 是如何產生?<br />
API: <a href="http://api.cakephp.org/view_source/security-component/#line-612">http://api.cakephp.org/view_source/security-component/#line-612</a></p>
<p>簡明點說, 沒有timestamp , 但有form 的每一個field, field 的name attribute. 所以你不可以自己加 input tags. 例子:</p>
<pre class="brush: php;">
&#60;?php
//add.ctp
  echo $form-&#62;create('page',array('url'=&#62;$this-&#62;here));
  echo $form-&#62;input('title');
  echo $form-&#62;input('check',array('type'=&#62;'checkbox'));
?&#62;
&#60;input name=&#34;data[page][abc]&#34; value=&#34;abc&#34; /&#62;
&#60;?php
  echo $form-&#62;end('submit');
?&#62;
</pre>
<p>便pass 不了有 security component 的 controller 了, 因為有一個field 不使用 $form-&#62;input()</p>
<p>第一眼看, 這樣沒有問題呀, 因為input 可以使用 $form-&#62;input(). 有很多設定(options)可以改變 input 的, div=&#62;false, label=&#62;false 等等. layout html 上應該沒有什麼限制</p>
<p>對, 所以我都只是找到一個情況會出亂子. 就是 checkbox:</p>
<pre class="brush: php;">
&#60;?php
$form-&#62;input('check',array('type'=&#62;'checkbox'));
?&#62;
</pre>
<p>會輸出兩個input tag, 一個hidden, 一個type 是checkbox. (v1.3 好像可以不輸出hidden field)</p>
<p>問題是, 兩個同一個name 的 input 會令某些 js validation framework 出亂子. 永遠都只看hidden 的 input tag (<a href="http://api.cakephp.org/view_source/form-helper/#line-871">因為 hidden 又一定在前面, type=&#8217;checkbox&#8217; 在後</a> ). 所以&#8230;改js validation</p>
<p>p.s. 最最後, 我發覺, 只要你的 input tag 不使用 data[model][name] 的方式命名. 便不會出現問題, 因為 security component 只找用這個方式命名的field 做 hash&#8230; 但 controller 的 $this-&#62;data 便不會出現這field (model 的validation 都不會經過..), 除非&#8230;</p>
<pre class="brush: php;">
//controller.php
function beforeFilter() {
  parent::beforeFilter();
  //unsafe!!! check exact equals of model and field name before merge
  //記得對清楚 model 和 field name 才 merge..
  $this-&#62;data = array_merge($this-&#62;data,$this-&#62;params[model]);
}
</pre>
<p>我的 case 不合用了, 我只需要使用者check了就好, 不需要走進DB, 直接check 了就pass, 否則fail</p>
<p>p.p.s: <a href="http://en.wikipedia.org/wiki/Cross-site_request_forgery">http://en.wikipedia.org/wiki/Cross-site_request_forgery</a></p>
<p>&#160;</p>
<p>&#160;</p>
</div>]]></content:encoded>
</item>

</channel>
</rss>
