環境設定
データベースの設定
CakePHPは、データベースの詳細設定ファイルをapp/config/database.phpに探します。データベースの設定例のファイルはapp/config/database.php.defaultにあります。設定が終わると次のようになります。
var $default = array('driver' => 'mysql',
'persistent' => false,
'host' => 'localhost',
'login' => 'cakephpuser',
'password' => 'c4k3roxx!',
'database' => 'my_cakephp_project',
'prefix' => '');
var $default = array('driver' => 'mysql','persistent' => false,'host' => 'localhost','login' => 'cakephpuser','password' => 'c4k3roxx!','database' => 'my_cakephp_project','prefix' => '');
$default接続配列は、モデル内で$useDbConfigの値を変更して別な接続を指定しない限り使用されます。例えば、アプリケーションがデフォルトのデータベースに加えて、既存(legacy)の追加データベースも使用しなければいけない、としましょう。$default配列と同形式で$legacyデータベース接続用の配列を作成します。それから、該当するモデルの中でvar $useDbConfig = ‘legacy’とすることで、それを使えるようになります。
必要に合わせて、設定配列の中に、キー/値のペアを書き込んでください。
| キー | 値 |
|---|---|
| driver | この設定用配列は、データベースのドライバ名を入力する場所です。例えば、mysql, postgres, sqlite, pear-drivername, adodb-drivername, mssql, oracle, odbc などです。 |
| persistent | 持続的接続(persistent connection)を使うかどうか設定します。 |
| host | データベースサーバのホスト名。(またはIPアドレス) |
| login | アカウントユーザ名 |
| password | アカウントのパスワード。 |
| database | この接続が利用するデータベース名。 |
| prefix (オプション) | データベース内のすべてのテーブルの頭に付ける接頭辞(prefix)です。もしテーブルに接頭辞が付いていないのであれば、指定しないでください。 |
| port (オプション) | サーバに接続するためのTCPポート、またはUnix socket。 |
| encoding | サーバにSQLステートメントを送信する際に使用するキャラクターセット。(訳注:MySQLで日本語を使うには、"utf8","ujis","sjis"などを設定します。) |
| schema | PostgreSQLデータベースの設定時に、どのスキーマを使うかを指定します。 |
prefixの設定は、モデルではなく、テーブルに対するものだということを覚えておきましょう。例えば、AppleモデルとFlavorモデルのjoinテーブルを作成する場合、prefix_apples_flavorsという名前になります。(prefix_apples_prefix_flavorsではありません。)そして、prefixの設定は、'prefix_'となります。
この時点で、このマニュアルの付録部分の一覧にある、CakePHPの規約について少し読むのもよいかもしれません。テーブル(そして幾つかのフィールド名)の正しい命名方法を知っておくと、幾つかの機能をすぐに使えるようになり、設定する必要がなくなります。
コアの設定
CalePHPのアプリケーション設定は、/app/config/core.phpの中にあります。このファイルは、アプリケーションの動作を決める、Configureクラスの変数定義と定数定義の集まりです。この各変数について設定する前に、CakePHPの環境設定レジストリクラス、Configureについてある程度知っておく必要があります。
Configurationクラス
CakePHPで設定しなければいけないことはそれほど多くありませんが、アプリケーションの中に独自のルールを設定できるようにしておくと、便利なことがあります。これまではカスタム設定に関する変数や定数をいくつかのファイルの中に定義していたかもしれませんが、そうすると、値が必要になるたびに、毎回、設定ファイルをincludeしなくてはならなくなります。
CakePHPの新しいConfigureクラスを使うと、アプリケーション、またその実行時に必要な特定の値の保存と取り出しに使うことができます。このクラスの中には何でも保存でき、コード内のあらゆる場所で使用できるので、CakePHPのMVCパターンを崩してしまう誘惑には注意しましょう。Configureクラスの主要な目標は、各変数を集中保管して、各オブジェクトから使用できるようにすることです。“設定より規約”(convention over configuration)を遵守するようにして、MVC構造を壊してしまうことがないようにしましょう。
このクラスは singleton として動作し、メソッドは静的なコンテキストとして、アプリケーション内のどこからでも呼ぶことができます。
<?php Configure::read('debug'); ?>
<?php Configure::read('debug'); ?>
Configureのメソッド
write
write(string $key, mixed $value)
write(string $key, mixed $value)
write()を使って、アプリケーションの設定データを保存します。
Configure::write('Company.name','株式会社ピザ');
Configure::write('Company.slogan','体と心にピザを');
Configure::write('Company.name','株式会社ピザ');Configure::write('Company.slogan','体と心にピザを');
$keyのパラメータとして、ドットを使っていることに注意してください。このドットを使って、論理グループごとに設定を整理することができます。
Configure::write(
'Company',array('name'=>'株式会社ピザ','slogan'=>'体と心にピザを')
);
Configure::write('Company',array('name'=>'株式会社ピザ','slogan'=>'体と心にピザを'));
Configure::write(‘debug’, $int)を使って、デバッグと運用モードをすぐに切り替えることができます。AMFやSOAPなどとの連携の際、デバッグ情報のためにパースに問題が生じるような場合に特に便利に使うことができます。
read
read(string $key = 'debug')
read(string $key = 'debug')
アプリケーションから、環境設定データを読み込むために使います。デフォルトでは、CakePHPの重要なデバッグ値が設定されています。keyが指定されると、そのデータが返されます。上のwrite()の例を使うと、返される次のようなデータを取得できます。
Configure::read('Company.name'); //出力は: '株式会社ピザ'
Configure::read('Company.slogan'); //出力は: '体と心にピザを'
Configure::read('Company');
//出力は:
array('name' => '株式会社ピザ', 'slogan' => '体と心にピザを');
Configure::read('Company.name'); //出力は: '株式会社ピザ'Configure::read('Company.slogan'); //出力は: '体と心にピザを'Configure::read('Company');//出力は:array('name' => '株式会社ピザ', 'slogan' => '体と心にピザを');
delete
delete(string $key)
delete(string $key)
アプリケーションの環境設定から情報を削除するのに使います。
Configure::delete('Company.name');
Configure::delete('Company.name');
load
load(string $path)
load(string $path)
指定したファイルから環境設定をloadするためにこのメソッドを使ってください。
// /app/config/messages.php:
<?php
$config['Company']['name'] = '株式会社ピザ';
$config['Company']['slogan'] = '体と心にピザを';
$config['Company']['phone'] = '555-55-55';
?>
<?php
Configure::load('messages');
Configure::read('Company.name');
?>
// /app/config/messages.php:<?php$config['Company']['name'] = '株式会社ピザ';$config['Company']['slogan'] = '体と心にピザを';$config['Company']['phone'] = '555-55-55';?><?phpConfigure::load('messages');Configure::read('Company.name');?>
ファイルの中では、$config配列のキーと配列のペアで設定されていることに注意してください。ファイル内のその他の変数は、load()では無視されます。
version
version()
version()
現在のアプリケーションのCakePHPのバージョンを返します。
CakePHP Core Configuration Variables
The Configure class is used to manage a set of core CakePHP configuration variables. These variables can be found in app/config/core.php. Below is a description of each variable, and how it’s usage affects your CakePHP application.
| Configure Variable | Description |
|---|---|
| debug |
Changes CakePHP debugging output. 0 = Production mode. No output. 1 = Show errors and warnings. 2 = Show errors, warnings, and SQL. 3 = Show errors, warnings, SQL, and complete controller dump. |
| App.baseUrl | Un-comment this definition if you don’t plan to use Apache’s mod_rewrite with CakePHP. Don’t forget to remove your .htaccess files too. |
| Routing.admin | Un-comment this definition if you’d like to take advantage of CakePHP admin routes. Set this variable to the name of the admin route you’d like to use. More on this later. |
| Cache.disable | When set to true, caching is disabled site-wide. |
| Cache.check | If set to true, enables view caching. Enabling is still needed in the controllers, but this variable enables the detection of those settings. |
| Session.save |
Tells CakePHP which session storage mechanism to use. php = Use the default PHP session storage. cake = Store session data in /app/tmp database = store session data in a database table. Make sure to set up the table using the SQL file located at /app/config/sql/sessions.sql. |
| Session.table | The name of the table (not including any prefix) that stores session information. |
| Session.database | The name of the database that stores session information. |
| Session.cookie | The name of the cookie used to track sessions. |
| Session.timeout | Base session timeout in seconds. Actual value depends on Security.level. |
| Session.start | Automatically starts sessions when set to true. |
| Session.checkAgent | When set to false, CakePHP sessions will not check to ensure the user agent does not change between requests. |
| Security.level |
The level of CakePHP security. The session timeout time defined in 'Session.timeout' is multiplied according to the settings here. Valid values: 'high' = x 10 'medium' = x 100 'low' = x 300 |
| Security.salt | A random string used in security hashing. |
| Acl.classname, Acl.database | Constants used for CakePHP’s Access Control List functionality. See the Access Control Lists chapter for more information. |
Note: Cache configuration is also found in core.php — We’ll be covering that later on, so stay tuned.
The Configure class can be used to read and write core configuration settings on the fly. This can be especially handy if you want to turn the debug setting on for a limited section of logic in your application, for instance.
Configuration Constants
While most configuration options are handled by Configure, there are a few constants that CakePHP uses during runtime.
| Constant | Description |
|---|---|
| LOG_ERROR | Error constant. Used for differentiating error logging and debugging. Currently PHP supports LOG_DEBUG. |
Routes Configuration
Routing is a feature that maps URLs to controller actions. It was added to CakePHP to make pretty URLs more configurable and flexible. Using Apache’s mod_rewrite is not required for using routes, but it will make your address bar look much more tidy.
Routes in CakePHP 1.2 have been expanded and can be very powerful.
Default Routing
Before you learn about configuring your own routes, you should know that CakePHP comes configured with a default set of routes. CakePHP’s default routing will get you pretty far in any application. You can access an action directly via the URL by putting its name in the request. You can also pass parameters to your controller actions using the URL.
URL pattern default routes:
http://example.com/controller/action/param1/param2/param3
URL pattern default routes:http://example.com/controller/action/param1/param2/param3
The URL /posts/view maps to the view() action of the PostsController, and /products/viewClearance maps to the view_clearance() action of the ProductsController. If no action is specified in the URL, the index() method is assumed.
The default routing setup also allows you to pass parameters to your actions using the URL. A request for /posts/view/25 would be equivalent to calling view(25) on the PostsController, for example.
New in CakePHP 1.2 is the ability to use named parameters. You can name parameters and send their values using the URL. A request for /posts/view/title:first+post/category:general would result in a call to the view() action of the PostsController. In that action, you’d find the values of the title and category parameters inside $this->passedArgs[‘title’] and $this->passedArgs[‘category’] respectively.
Some summarizing examples for default routes might prove helpful.
URL to controller action mapping using default routes:
URL: /monkeys/jump
Mapping: MonkeysController->jump();
URL: /products
Mapping: ProductsController->index();
URL: /tasks/view/45
Mapping: TasksController->view(45);
URL: /donations/view/recent/2001
Mapping: DonationsController->view('recent', '2001');
URL: /contents/view/chapter:models/section:associations
Mapping: ContentsController->view();
$this->passedArgs['chapter'] = 'models';
$this->passedArgs['section'] = 'associations';
URL to controller action mapping using default routes:URL: /monkeys/jumpMapping: MonkeysController->jump();URL: /productsMapping: ProductsController->index();URL: /tasks/view/45Mapping: TasksController->view(45);URL: /donations/view/recent/2001Mapping: DonationsController->view('recent', '2001');URL: /contents/view/chapter:models/section:associationsMapping: ContentsController->view();$this->passedArgs['chapter'] = 'models';$this->passedArgs['section'] = 'associations';
Defining Routes
Defining your own routes allows you to define how your application will respond to a given URL. Define your own routes in the /app/config/routes.php file using the Router::connect() method.
The connect() method takes up to three parameters: the URL you wish to match, the the default values for custom route elements, and regular expression rules to help the router match elements in the URL.
The basic format for a route definition is:
Router::connect(
'URL',
array('paramName' => 'defaultValue'),
array('paramName' => 'matchingRegex')
)
Router::connect('URL',array('paramName' => 'defaultValue'),array('paramName' => 'matchingRegex'))
The first parameter is used to tell the router what sort of URL you’re trying to control. The URL is a normal slash delimited string, but can also contain a wildcard (*) or custom route elements (URL elements prefixed with a colon). Using a wildcard tells the router what sorts of URLs you want to match, and specifying route elements allows you to gather parameters for your controller actions.
Once you’ve specified a URL, you use the last two parameters of connect() to tell CakePHP what to do with a request once it has been matched. The second parameter is an associative array. The keys of the array should be named after the route elements in the URL, or the default elements: :controller, :action, and :plugin. The values in the array are the default values for those keys. Let’s look at some basic examples before we start using the third parameter of connect().
Router::connect(
'/pages/*',
array('controller' => 'pages', 'action' => 'display')
);
Router::connect('/pages/*',array('controller' => 'pages', 'action' => 'display'));
This route is found in the routes.php file distributed with CakePHP (line 40). This route matches any URL starting with /pages/ and hands it to the display() method of the PagesController(); The request /pages/products would be mapped to PagesController->display(‘products’), for example.
Router::connect(
'/government',
array('controller' => 'products', 'action' => 'display', 5)
);
Router::connect('/government',array('controller' => 'products', 'action' => 'display', 5));
This second example shows how you can use the second parameter of connect() to define default parameters. If you built a site that features products for different categories of customers, you might consider creating a route. This allows you link to /government rather than /products/display/5.
For additional flexibility, you can specify custom route elements. Doing so gives you the power to define places in the URL where parameters for controller actions should lie. When a request is made, the values for these custom route elements are found in $this->params of the controller. This is different than named parameters are handled, so note the difference: named parameters (/controller/action/name:value) are found in $this->passedArgs, whereas custom route element data is found in $this->params. When you define a custom route element, you also need to specify a regular expression - this tells CakePHP how to know if the URL is correctly formed or not.
Router::connect(
'/:controller/:id',
array('action' => 'view'),
array('id' => '[0-9]+')
);
Router::connect('/:controller/:id',array('action' => 'view'),array('id' => '[0-9]+'));
This simple example illustrates how to create a quick way to view models from any controller by crafting a URL that looks like /controllername/id. The URL provided to connect() specifies two route elements: :controller and :id. The :controller element is a CakePHP default route element, so the router knows how to match and identify controller names in URLs. The :id element is a custom route element, and must be further clarified by specifying a matching regular expression in the third parameter of connect(). This tells CakePHP how to recognize the ID in the URL as opposed to something else, such as an action name.
Once this route has been defined, requesting /apples/5 is the same as requesting /apples/view/5. Both would call the view() method of the ApplesController. Inside the view() method, you would need to access the passed ID at $this->params[‘id’].
One more example, and you’ll be a routing pro.
Router::connect(
'/:controller/:year/:month/:day',
array('action' => 'index', 'day' => null),
array(
'year' => '[12][0-9]{3}',
'month' => '(0[1-9]|1[012])',
'day' => '(0[1-9]|[12][0-9]|3[01])'
)
);
Router::connect('/:controller/:year/:month/:day',array('action' => 'index', 'day' => null),array('year' => '[12][0-9]{3}','month' => '(0[1-9]|1[012])','day' => '(0[1-9]|[12][0-9]|3[01])'));
This is rather involved, but shows how powerful routes can really become. The URL supplied has four route elements. The first is familiar to us: it’s a default route element that tells CakePHP to expect a controller name.
Next, we specify some default values. Regardless of the controller, we want the index() action to be called. We set the day parameter (the fourth element in the URL) to null to flag it as being optional.
Finally, we specify some regular expressions that will match years, months and days in numerical form.
Once defined, this route will match /articles/2007/02/01, /posts/2004/11/16, and /products/2001/05 (remember that the day parameter is optional?), handing the requests to the index() actions of their respective controllers, with the custom date parameters in $this->params.
Prefix Routing
Many applications require an administration section where priveledged users can make changes. This is often done through a special URL such as /admin/users/edit/5. In CakePHP, admin routing can be enabled from within the core configuration file by setting the admin path for Routing.admin.
Configure::write('Routing.admin', 'admin'); Configure::write('Routing.admin', 'admin');
In your controller, any action with an admin_ prefix will be called. Using our users example, the method name of our UsersController would be admin_edit.
You can use the Router to use custom prefixes for uses beyond admin routing, too.
Router::connect('/profiles/:controller/:action', array('prefix' => 'profiles')); Router::connect('/profiles/:controller/:action', array('prefix' => 'profiles'));
Any calls to the profiles section would look for the profiles_ prefix on the method calls. Our users example would have a URL structure that looks like /profiles/users/edit/5 would call the profiles_edit method within the UsersController. Also important to remember, using the HTML helper to build your links will help maintain the prefix calls. Here's an example link being built using the HTML helper:
echo $html->link('Edit your profile', array('controller' => 'users', 'action' => 'profiles_edit')); echo $html->link('Edit your profile', array('controller' => 'users', 'action' => 'profiles_edit'));
You can set up multiple prefixed routes using this approach to create a flexible URL structure for your application.
Custom Inflections
Cake's naming conventions can be really nice - you can name your database table big_boxes, your model BigBox, your controller BigBoxesController, and everything just works together automatically. The way CakePHP knows how to tie things together is by inflecting the words between their singular and plural forms.
There are occasions (especially for our non-English speaking friends) where you may run into situations where CakePHP's inflector (the class that pluralizes, singularizes, camelCases, and under_scores) might not work as you'd like. If CakePHP won't recognize your Foci or Fish, editing the custom inflections configuration file is where you can tell CakePHP about your special cases. This file is found in /app/config/inflections.php.
In this file, you will find six variables. Each allows you to fine-tune CakePHP inflection behavior.
| inflections.php Variable | Description |
|---|---|
| $pluralRules | This array contains regular expression rules for pluralizing special cases. The keys of the array are patterns, and the values are replacements. |
| $uninflectedPlural | An array containing words that do not need to be modified in order to be plural (mass nouns, etc.). |
| $irregularPlural | An array containing words and their plurals. The keys of the array contain the singular form, the values, plural forms. This array should be used to store words that don’t follow rules defined in $pluralRules. |
| $singularRules | Same as with $pluralRules, only this array holds rules that singularize words. |
| $uninflectedSingular | Same as with $uninflectedPlural, only this array holds words that have no singular form. This is set equal to $uninflectedPlural by default. |
| $irregularSingular | Same as with $irregularPlural, only with words in singular form. |
Bootstrapping CakePHP
If you have any additional configuration needs, use CakePHP’s bootstrap file, found in /app/config/bootstrap.php. This file is executed just after CakePHP’s core bootstrapping.
This file is ideal for a number of common bootstrapping tasks:
- Defining convenience functions
- Registering global constants
- Defining additional model, view, and controller paths
Be careful to maintain the MVC software design pattern when you add things to the bootstrap file: it might be tempting to place formatting functions there in order to use them in your controllers.
Resist the urge. You’ll be glad you did later on down the line.
You might also consider placing things in the AppController class. This class is a parent class to all of the controllers in your application. AppController is handy place to use controller callbacks and define methods to be used by all of your controllers.

login to add a comment