The CheatSheet - CakePHP 1.2

Posted at 2009/10/20 09:26 // in 웹프로그래밍™/CakePHP // by 블루비
CakePHP 1.2 Cheatsheet

CakePHP 1.2 Cheatsheet





http://cakephp.org/files/Resources/CakePHP-1.2-Cheatsheet.pdf

2009/10/20 09:26 2009/10/20 09:26

댓글을 남겨주세요.

[로그인][오픈아이디란?]

CakePHP Email Encoding

Posted at 2009/10/01 08:55 // in 웹프로그래밍™/CakePHP // by 블루비

$
this->Email->charset = 'utf-8';

$this->Email->from = '블루비 <blog @ blueb . net>';
$this->Email->to = '블루비 <blog @ blueb . net>';
$this->Email->subject = 'CakePHP Email Test';
$this->Email->template = 'test'; //views/elements/email/html/test.ctp
$this->Email->sendAs = 'both'; // text, html or both
$this->Email->send();

2009/10/01 08:55 2009/10/01 08:55

댓글을 남겨주세요.

[로그인][오픈아이디란?]

IIS7 + CakePHP + URL Rewrite

Posted at 2009/08/04 12:47 // in 웹프로그래밍™/CakePHP // by 블루비
Windows Server 2008에서 CakePHP를 서비스 할 수 있습니다.
IIS7에는 URL Rewrite 모듈을 추가 하여 Apache Mod_Rewrite 모듈과 같이 Fancy URL을 사용할 수 있습니다.


사용자 삽입 이미지
URL Rewrite 모듈을 다운 받아 설치 하시면 위에 보시는 봐와 같이 URL Rewrite 가 보입니다.

사용자 삽입 이미지
CakePHP의 Fancy URL을 사용하기 위해 URL Rewrite 모듈을 이용하여 Rule을 추가 해줍니다.
위 모듈을 설정하시면 web root 에 web.config xml 파일에 생성이 됩니다.
처음 UI 패널을 통해 등록하시기는 좀 어려우시니 web.config 파일에 직접 등록하셔되 됩니다.

web.config 파일 소스입니다.
<?xml version="1.0" encoding="UTF-8"?>
<configuration>
<system.webServer>
<defaultDocument>
<files>
<add value="index.php" />
</files>
</defaultDocument>
<rewrite>
<rules>
<rule name="Imported Rule CSS" stopProcessing="true">
<match url="^css(.*)$" ignoreCase="false" />
<action type="Rewrite" url="webroot/css{R:1}" />
</rule>
<rule name="Imported Rule JS" stopProcessing="true">
<match url="^js(.*)$" ignoreCase="false" />
<action type="Rewrite" url="webroot/js{R:1}" />
</rule>
<rule name="Imported Rule IMG" stopProcessing="true">
<match url="^img(.*)$" ignoreCase="false" />
<action type="Rewrite" url="webroot/img{R:1}" />
</rule>
<rule name="Imported Rule Images" stopProcessing="true">
<match url="^images(.*)$" ignoreCase="false" />
<action type="Rewrite" url="webroot/images{R:1}" />
</rule>
<rule name="Imported Rule Flash" stopProcessing="true">
<match url="^flash(.*)$" ignoreCase="false" />
<action type="Rewrite" url="webroot/flash{R:1}" />
</rule>
<rule name="Imported Rule Files" stopProcessing="true">
<match url="^files(.*)$" ignoreCase="false" />
<action type="Rewrite" url="webroot/files{R:1}" />
</rule>


<rule name="Imported Rule 3" stopProcessing="true">
<match url="^(.*)$" ignoreCase="false" />
<conditions logicalGrouping="MatchAll">
<add input="{REQUEST_FILENAME}" matchType="IsDirectory" negate="true" pattern="" ignoreCase="false" />
<add input="{REQUEST_FILENAME}" matchType="IsFile" negate="true" pattern="" ignoreCase="false" />
</conditions>
<action type="Rewrite" url="index.php?url={R:1}" appendQueryString="true" />
</rule>
</rules>
</rewrite>
<handlers>
<add name="php5" path="*.php" verb="*" modules="FastCgiModule" scriptProcessor="C:\PHP\php-cgi.exe" resourceType="Unspecified" />
</handlers>
<httpProtocol>
<customHeaders>
<remove name="X-Powered-By" />
</customHeaders>
</httpProtocol>
</system.webServer>
</configuration>

Default 문서를 셋팅하기 위해 아래 내용도 같이 추가 해주시면 됩니다

<defaultDocument>
<files>
<add value="index.php" />
</files>
</defaultDocument>


사용자 삽입 이미지
IIS7 에서 PHP를 실행 할 수 있도록 http://windows.php.net/download/ 에서 VC9 x86 Non Thread Safe Zip 파일을 다운받아 c:\PHP 폴더를 만들고 압출을 풀어 "처리기 매핑"을 통해 모듈매핑추가를 해줍니다.
2009/08/04 12:47 2009/08/04 12:47

댓글을 남겨주세요.

[로그인][오픈아이디란?]

[CakePHP] multiple language url connection : /lang/controller/action

Posted at 2009/07/08 10:13 // in 웹프로그래밍™/CakePHP // by 블루비
CakePHP 를 다국어로 접속가능 하도록 하기 위한 설정내용입니다.

일반적으로 uri 접속시 /controller/action 으로 접속하게 됩니다.
언어별 접속을을 위해 /lang/controller/action 과 같이 controller가 아닌 language로 시작할 수 있습니다.


언어별 약어 표현은 ISO 639-2 Language Code 참조 하세요


1. 기본 언어를 설정하기 위해 core.php 파일에 아래 코드를 추가합니다.
app/config/core.php
Configure::write('Config.language', 'kor');

2. /lang/controller/action 과 같은 url 접속을 위해 router.php 파일에 아래 코드를 추가합니다.
app/config/router.php
Router::connect('/:language/:controller/:action/*', array(), array('language' => '[a-z]{3}'));

3. 언어별 접속시 switching 하기위해서 app_controller.php 파일에 아래 코드를 추가합니다.
(app_controller.php 파일이 없는 경우는 생성합니다.)
app/app_controller.php
class AppController extends Controller {

function beforeFilter(){
$this->_setLanguage();
}

function _setLanguage() {

if ( $this->Cookie->read('lang') && !$this->Session->check('Config.language')){
$this->Session->write('Config.language', $this->Cookie->read('lang'));
}
else if( isset($this->params['language'] ) && ($this->params['language'] != $this->Session->read('Config.language')) ){
$this->Session->write('Config.language', $this->params['language']);
$this->Cookie->write('lang', $this->params['language'], true, '20 days');
}
else if ( !isset($this->params['language']) && isset($this->params['named']['language']) && ($this->params['named']['language'] != $this->Session->read('Config.language'))) {
$this->Session->write('Config.language', $this->params['named']['language']);
$this->Cookie->write('lang', $this->params['named']['language'], true, '20 days');
}
else if( !isset($this->params['language']) && !isset($this->params['named']['language']) && $this->Cookie->read('lang') != Configure::Read('Config.language') ){
$this->Session->write('Config.language', Configure::Read('Config.language'));
$this->Cookie->write('lang', Configure::Read('Config.language'), true, '20 days');
}

}
}//end of class AppController

4. 각 언어별 default.po 파일을 생성합니다.
msgid , msgstr 을 이용하여 메시지 내용을 셋팅합니다.
/app/locale/eng/LC_MESSAGES/default.po
msgid "num"
msgstr "No"

msgid "file"
msgstr "File"
/app/locale/kor/LC_MESSAGES/default.po
msgid "num"
msgstr "번호"

msgid "file"
msgstr "파일"

5. view 파일에서 __() 메쏘드와 locale의 msgid를 사용합니다.
<?=__("num");?> >> 번호
<?=$this->link(__("num",true),array('/'));?> >> <a href="/">번호</a>

6. 각 언어별로 접속시 자동으로 언어별 메시지가 switching 됩니다.
http://blueb.net/controller/action (kor language)
http://blueb.net/eng/controller/action (eng language)




2009/07/08 10:13 2009/07/08 10:13

댓글을 남겨주세요.

[로그인][오픈아이디란?]

CakePHP를 위한 OpenID component

Posted at 2009/06/18 11:16 // in 웹프로그래밍™/CakePHP // by 블루비
CakePHP 에서 사용할 수 있는 OpenID 컴포넌트 입니다.

설치 방법

  • OpenID component 를 다운받습니다.
  • “app/controllers/components” 위치에 다운받은 openid.php 파일을 복사 합니다.
  • PHP OpenID Library 2.1.x 를 다운 받습니다.
  • “Auth” 디렉토리를 “vendors” 디렉토리에 복사합니다.
  • “Auth/OpenID/Consumer.php” 파일 소스을 변경해주세요
    if (Auth_OpenID::arrayGet($q, $key) != $value) {

    on line 922 with

    if ($key != 'url' && Auth_OpenID::arrayGet($q, $key) != $value) {
  • EAUT library 를 다운받은 후 , Email.php 파일을 Auth/Yadis 디렉토리에 복사합니다.
  • controller(s) 에서 component 를 추가하여 사용할 수 있습니다:
    public $components = array('Openid');

사용 예제

Login form (app/views/users/login.ctp):

<?php
if (isset($message)) {
echo '<p class="error">'.$message.'</p>';
}
echo $form->create('User', array('type' => 'post', 'action' => 'login'));
echo $form->input('OpenidUrl.openid', array('label' => false));
echo $form->end('Login');
?>

And the controller (app/controllers/users_controller.php):

<?
class UsersController extends AppController {
public $components = array('Openid');
public $uses = array();

public function login() {
$returnTo = 'http://'.$_SERVER['SERVER_NAME'].'/users/login';

if (!empty($this->data)) {
try {
$this->Openid->authenticate($this->data['OpenidUrl']['openid'], $returnTo, 'http://'.$_SERVER['SERVER_NAME']);
} catch (InvalidArgumentException $e) {
$this->setMessage('Invalid OpenID');
} catch (Exception $e) {
$this->setMessage($e->getMessage());
}
} elseif (count($_GET) > 1) {
$response = $this->Openid->getResponse($returnTo);

if ($response->status == Auth_OpenID_CANCEL) {
$this->setMessage('Verification cancelled');
} elseif ($response->status == Auth_OpenID_FAILURE) {
$this->setMessage('OpenID verification failed: '.$response->message);
} elseif ($response->status == Auth_OpenID_SUCCESS) {
echo 'successfully authenticated!';
exit;
}
}
}

private function setMessage($message) {
$this->set('message', $message);
}
}
?>
2009/06/18 11:16 2009/06/18 11:16

댓글을 남겨주세요.

[로그인][오픈아이디란?]

[CakePHP] Dynamic validation rules

Posted at 2009/06/16 20:45 // in 웹프로그래밍™/CakePHP // by 블루비
모델에서 선언된 validate 를 변경하고 싶다면,
다음과 같이 Controller 에서 Set::merge() 를 통해 재정의 해주면 됩니다.


$this->Profile->validate = Set::merge($this->Profile->validate, array(
'name'=>array(
'required'=>true,
'rule'=>array('alphaNumeric')
)
));





2009/06/16 20:45 2009/06/16 20:45

댓글을 남겨주세요.

[로그인][오픈아이디란?]

[CakePHP] 조인문 추가 작성을 위한 bindModel tip

Posted at 2009/06/02 15:44 // in 웹프로그래밍™/CakePHP // by 블루비

CakePHP 테이블 조인을 추가로 작성 하기 위해 bindModel()을 이용하여 작성할 수 있습니다.
하지만, 페이징(paginate) 처리시 bindModel()을 이용하게 되면 적상 적으로 조인문에 대한 쿼리가 적용되지 않습니다.
$this->Board->bindModel(array(
'hasOne'=>array('[ClassName]'=>array('foreignKey'=>'id'))
));

원인은 bind/unbind 시에 쿼리 한번만 유호하게 됩니다.
paginate 에서는 쿼리를 두번 날리도록 되어 있습니다.
첫번째 쿼리는 레코드수를 가져오고 두번째 쿼리는 limit 된 쿼리를 날리게 됩니다.
따라서 레코드수를 가져오는 쿼리에서는 정상적으로 조인문에 추가된 반면 두번째 쿼리에서는 추가된 조인문이 적용 되지 않습니다.

이문제를 해결하는 방법은 간단합니다. bindModel()의 두번재 인자에 false 값을 주는것으로 bindModel을 지속시켜 줍니다.

$this->Board->bindModel(array(
'hasOne'=>array('[ClassName]'=>array('foreignKey'=>'id'))
),false);



2009/06/02 15:44 2009/06/02 15:44

댓글을 남겨주세요.

[로그인][오픈아이디란?]

[CakePHP] radio 버튼 checked 옵션 사용법

Posted at 2009/05/18 09:12 // in 웹프로그래밍™/CakePHP // by 블루비
CakePHP Form Helper 에서 지원하는 radio 메쏘드에는 checked 옵션이 포함되어 있지 않습니다.
그래서 $form->radio() 아닌 $form->input() 을 사용하여 해결해야 합니다.

아래 코드와 같이 $form->input() 의 옵션에 default 옵션을 추가 하여 해당 값을 지정함으로 checked 가 되어 집니다.

$form->input('Model.field',array (
'legend'=>false,
'type'=>'radio',
'options'=>array(
'val1'=>'label1',
'val2'=>'label2'
),
'default'=>'val2')))


참조 : http://anjella.co.kr/283
2009/05/18 09:12 2009/05/18 09:12
  1. 안젤라

    2009/05/19 11:16 [수정/삭제] [답글]

    이거땜시 저도 좀 고민했었죠~~~ ^^도움이 되셔서 좋네요~

  2. 안젤라

    2009/09/02 16:17 [수정/삭제] [답글]

    제가 블로그를 티스토리로 옮겼어요. 그래서 하위 디렉토리 tc 없이 그냥 글번호를 붙여주면 그 글로 갑니다. ^^

    http://anjella.co.kr/tc/283
    => http://anjella.co.kr/283

댓글을 남겨주세요.

[로그인][오픈아이디란?]

CakePHP DB 커넥션 Character Set 설정

Posted at 2009/03/17 23:52 // in 웹프로그래밍™/CakePHP // by 블루비
CakePHP DB 커넥션 Character Set 설정

var $default = array(
'driver' => 'mysql',
'connect' => 'mysql_connect',
'host' => 'localhost',
'login' => 'id',
'password' => 'passwd',
'database' => 'dbname',
'encoding' => 'UTF8',
'prefix' => ''
);

2009/03/17 23:52 2009/03/17 23:52

댓글을 남겨주세요.

[로그인][오픈아이디란?]

[CAKEPHP] Model 동적 테이블 설정

Posted at 2009/03/17 10:54 // in 웹프로그래밍™/CakePHP // by 블루비
동일한 타입의 다수 테이블을 제어 하기 위해 각 테이블 수 만큼의 Model를 생성하지 않고 하나의 Model를 생성후
모델에서 사용되는 테이블을 컨트롤러에서 변경할 수 있다

다시 말해 하나에 모델을 가지고 같은 타입의 테이블을 제어 할 수 있게 된다..



class BoardsController extends AppController {
var uses = array('Upload');

function upload(){
$this->Upload->setSource('board_files'); //board_files 테이블을 Upload 모델 테이블로 셋팅
$this->Upload->save($this->data);
}
}


class ProductsController extends AppController {
var uses = array('Upload');

function upload(){
$this->Upload->setSource('product_files'); //product_files 테이블을 Upload 모델 테이블로 셋팅
$this->Upload->save($this->data);
}
}

2009/03/17 10:54 2009/03/17 10:54

댓글을 남겨주세요.

[로그인][오픈아이디란?]

[CakePHP] multiple DB connections models

Posted at 2009/02/18 14:52 // in 웹프로그래밍™/CakePHP // by 블루비

CakePHP 에서 다중 데이터 베이스에 접근을 이용하기 위한 방법입니다...



In this tutorial we will see how you can grab your data from different/multiple DB connections in the same application.

This is particularly usefull if you need to integrate your application with an existing system: let's immagine for example that your application needs to retrieve users data, and that the users data are shared by the general system you are integrating to in a different DB.

Let's get more real. The general application runs on a DB called DB_2, while your CakePHP application runs on DB_1. Users data are in DB_2, while all your app data are in DB_1.

First of all you need to specify 2 (or more DB connections) in app/config/database.php

class DATABASE_CONFIG {

var $default = array(
'driver' => 'mysql',
'persistent' => false,
'host' => 'your_host',
'login' => 'your_login_1',
'password' => 'your_password_1',
'database' => 'DB_1',
'prefix' => ''
);

var $general_syst = array(
'driver' => 'mysql',
'persistent' => false,
'host' => 'your_host',
'login' => 'your_login_2',
'password' => 'your_password_2',
'database' => 'DB_2',
'prefix' => ''
);
}
?>

By default CakePHP uses the 'default' connection in your models, if it exists in your database.php configuration.

An important thing is that if you use multiple DB connections in your models you should not set their connection as persistent: namely the 'persistent' key of your dB_connection array should be set to false.

This avoids that your application will use persistently the last connection you switched to in your models.

The key variable that will switch DB config in your models is: $useDbConfig

But let's build our User model and our Post model. They will respectively use:

  • User model: general_syst connection
  • Post model: default connection

User model (in app/models/user.php):

class User extends AppModel {

var $name = 'User';
var $useDbConfig = 'general_syst';

//your code here
//....
}

Post model (in app/models/post.php):

class Post extends AppModel {

var $name = 'Post';
var $useDbConfig = 'default';

//your code here
//....
}

In the Post model it wasn't really necessary to specify the $useDBconfig variable, because we CakePHP uses the 'default' DB config if nothing else is specified, but I specified it just to make the example clearer.

Right! Noe every time you will use in your controllers:

  • $this->Post->bla_bla_bla : data will be retrieved/inserted/updated from DB_1
  • $this->User->bla_bla_bla : data will be retrieved/inserted/updated from DB_2

출처 : http://www.4webby.com/blog/posts/view/6/cakephp_models_using_multiple_db_connections


2009/02/18 14:52 2009/02/18 14:52

댓글을 남겨주세요.

[로그인][오픈아이디란?]

[CakePHP] SwfUpload 업로드시 세션정보 사라지는 현상 해결 방법

Posted at 2009/02/12 12:41 // in 웹프로그래밍™/CakePHP // by 블루비
SwfUpload 를 통해 파일 업로드시 IE 에서만 세션(Session)정보가 파기 되는 문제가 발생합니다.

FireFox,Opera 등 타 브라우져에서는 문제가 없지만 IE만 이런 문제가 있는 듯합니다.
SwfUpload 사이트에 Flash Cookie Fug 글에서 관련정보를 찾으시면 됩니다.
http://swfupload.org/forum/generaldiscussion/383

그렇다면 이 문제를 해결하기 위해서는 어떻게 해야 할까요?

CakePHP 에서는 컨트롤러의 beforeFilter() 함수에 세션을 시작하는 코드 한줄만 추가 하면 이문제를 해결 할 수 있습니다.
주의할점은 parent::beforeFilter() 호출 전에 코드를 넣어 주어야 합니다.


<?php
# app/controllers/uploads_controller.php
class UploadsController extends AppController {

var $name = 'Uploads';
var $components = array('SwfUpload');
var $helpers = array('Html', 'Javascript');

function beforeFilter() {

if ($this->action == 'upload') { //upload Action 에서만 반응 하도록 처리
$this->Session->start(); //SwfUpload 의 세션정보를 유지하기 위한 코드
}

parent::beforeFilter();

}

function upload() {

if (isset($this->params['form']['Filedata'])) {
// process your upload in here
// and you can read from or write to the session
// as you would normally
}

?>
}

}
?>


2009/02/12 12:41 2009/02/12 12:41

댓글을 남겨주세요.

[로그인][오픈아이디란?]

[CakePHP] BETWEEN CONDITIONS

Posted at 2009/02/10 17:37 // in 웹프로그래밍™/CakePHP // by 블루비
CakePHP 데이터 베이스 쿼리 중 BETWEEN 조건절을 사용할 경우 아래와 같이 사용하면 됩니다.
$conditions = array('date BETWEEN ? AND ?' =>
array(
date('Y-m-d', strtotime('-1 weeks')),
date('Y-m-d', strtotime('now'))
)
);

$this->findAll($conditions);
..

2009/02/10 17:37 2009/02/10 17:37

댓글을 남겨주세요.

[로그인][오픈아이디란?]

CakePHP + IIS, Rewrite 모듈 사용

Posted at 2009/02/06 12:43 // in 웹프로그래밍™/CakePHP // by 블루비
ISAPI_Rewrite


http://blog.localkinegrinds.com/2006/07/28/cakephp-and-iis-solved/

more..




http://www.dustinweber.com/web-development/cakephp/cakephp-on-iis-troubleshooting-help-guide/



more..




http://yelotofu.com/2007/08/clean-urls-with-cakephp-and-iis/


more..




2009/02/06 12:43 2009/02/06 12:43
  1. aka.Gillyz

    2009/02/06 11:43 [수정/삭제] [답글]

    쪼앙~~!!! 후루루짭짭

댓글을 남겨주세요.

[로그인][오픈아이디란?]

CakePHP Contorller extend

Posted at 2009/01/22 00:14 // in 웹프로그래밍™/CakePHP // by 블루비

사용자가 추가한 컨트롤러의 확장 컨트롤러를 사용하고 싶다면 App::import('Controller','컨트롤러 명'); 을 사용하면 된다.


<?
// /app/projects_controller.php
App::import('Controller','Pages');
class ProjectsController extends PagesController {

}
?>
2009/01/22 00:14 2009/01/22 00:14

댓글을 남겨주세요.

[로그인][오픈아이디란?]