開発メモ,主に補足by子連れ親父プログラマー

2011-09-09

CakePHP1.3で作る会員管理システム(6) bakeする(controller,view)

bakeする(controller,view)

次に bake のメニューから、 C を選んでコントローラを作ります。

> C
---------------------------------------------------------------
Bake Controller
Path: /Users/myname/Sites/cake/app/controllers/
---------------------------------------------------------------
Possible Controllers based on your current database:
1. Favorites
2. Members
3. MembersFavorites
4. Types
5. Users
Enter a number from the list above,
type in the name of another controller, or 'q' to exit  
[q] > 2

モデルの時と同様の選択画面になるので、

2. Members
を選択します。

---------------------------------------------------------------
Baking MembersController
---------------------------------------------------------------
Would you like to build your controller interactively? (y/n) 
[y] > y

とりあえずYESですね。

Would you like to use dynamic scaffolding? (y/n) 
[n] > n

スキャフォルドをするかどうかですが、しないのでNOです。

Would you like to create some basic class methods 
(index(), add(), view(), edit())? (y/n) 
[n] > y

indexとかaddとかの基本のアクションを作るかどうかですね。ここでYESです。

Would you like to create the basic class methods for admin routing? (y/n) 
[n] > y

adminルーティングを使うかどうかです。これはYESです。

Would you like this controller to use other helpers
besides HtmlHelper and FormHelper? (y/n) 
[n] > n
Would you like this controller to use any components? (y/n) 
[n] > n
Would you like to use Session flash messages? (y/n) 
[y] > y

---------------------------------------------------------------
The following controller will be created:
---------------------------------------------------------------
Controller Name:
 Members
---------------------------------------------------------------
Look okay? (y/n) 
[y] > y

その後はそのままです。 /app/controllers/members_controller.php が作られました。

次に、 V を選んでビューを作ります。

> V
---------------------------------------------------------------
Bake View
Path: /Users/myname/Sites/cake/app/views/
---------------------------------------------------------------
Possible Controllers based on your current database:
1. Favorites
2. Members
3. MembersFavorites
4. Types
5. Users
Enter a number from the list above,
type in the name of another controller, or 'q' to exit  
[q] > 2

やはり2番のMembersを選んで進みます。

Would you like bake to build your views interactively?
Warning: Choosing no will overwrite Members views if it exist. (y/n) 
[n] > y

ここはYESにします。

Would you like to create some CRUD views
(index, add, view, edit) for this controller?
NOTE: Before doing so, you'll need to create your controller
and model classes (including associated models). (y/n) 
[y] > y

ここもとりあえずYESにします。

Would you like to create the views for admin routing? (y/n) 
[n] > y

admin 用のviewを作るかどうかです。これもYESにします。

/app/views/ 以下に members というフォルダーが作られ、 index.ctp 他の各アクション用ビューが自動生成されます。 登録フォームの view は以下のようになりました。

<div class="members form">
<?php echo $this->Form->create('Member');?>
 <fieldset>
  <legend><?php __('Add Member'); ?></legend>
 <?php
  echo $this->Form->input('email');
  echo $this->Form->input('password');
  echo $this->Form->input('type_id');
  echo $this->Form->input('birthday');
  echo $this->Form->input('img1');
  echo $this->Form->input('img2');
  echo $this->Form->input('Favorite');
 ?>
 </fieldset>
<?php echo $this->Form->end(__('Submit', true));?>
</div>
<div class="actions">
 <h3><?php __('Actions'); ?></h3>
 <ul>

  <li><?php echo $this->Html->link(__('List Members', true), array('action' => 'index'));?></li>
  <li><?php echo $this->Html->link(__('List Types', true), array('controller' => 'types', 'action' => 'index')); ?> </li>
  <li><?php echo $this->Html->link(__('New Type', true), array('controller' => 'types', 'action' => 'add')); ?> </li>
  <li><?php echo $this->Html->link(__('List Favorites', true), array('controller' => 'favorites', 'action' => 'index')); ?> </li>
  <li><?php echo $this->Html->link(__('New Favorite', true), array('controller' => 'favorites', 'action' => 'add')); ?> </li>
 </ul>
</div>

users についても同じようにしてコントローラとビューを作ります。

2011-09-05

CakePHP1.3で作る会員管理システム(5) bakeする(model)

bakeする(model)

続いてbakeしてモデル、コントローラ、ビューを作ります。
作るんですが、その前にマスターにデータを入れておきます。
テーブルの types と favorites は、値が入ってるだけのマスターテーブルです。
今回これの管理機能は提供しません。
ということで最初にテーブルにデータを入れておきます。
別に普通にSQLのinsert文で入れておくだけです。

INSERT INTO types (id, name) VALUES (1, '一般');
INSERT INTO types (id, name) VALUES (2, '専門');
INSERT INTO favorites (id, name) VALUES (1, 'apple');
INSERT INTO favorites (id, name) VALUES (2, 'orange');
INSERT INTO favorites (id, name) VALUES (3, 'grape');

で、最初にmembersテーブルのモデルから作ります。

cd Sites/cake/app
cake bake
と打つと、
Welcome to CakePHP v1.3.11 Console
---------------------------------------------------------------
App : app
Path: /Users/myname/Sites/cake/app
---------------------------------------------------------------
Interactive Bake Shell
---------------------------------------------------------------
[D]atabase Configuration
[M]odel
[V]iew
[C]ontroller
[P]roject
[F]ixture
[T]est case
[Q]uit
What would you like to Bake? (D/M/V/C/P/F/T/Q) 
> 
と表示されて入力待ちになるので、 M を入れます。
> M
---------------------------------------------------------------
Bake Model
Path: /Users/myname/Sites/cake/app/models/
---------------------------------------------------------------
Possible Models based on your current database:
1. Favorite
2. Member
3. MembersFavorite
4. Type
5. User
Enter a number from the list above,
type in the name of another model, or 'q' to exit  
[q] >
となるのでここで2番を選びます。

あとは対話しながら選択していくだけです。

A displayField could not be automatically detected
would you like to choose one? (y/n) 
> y
displayField が自動で見つけられなかった、自分で選ぶかい? と聞かれるのでyesとすると、
1. id
2. email
3. password
4. type_id
5. birthday
6. img1
7. img2
8. created
9. modified
Choose a field from the options above:  
> 2
members テーブルのカラム名が一覧されるので、2番の email を選択します。

Would you like to supply validation criteria 
for the fields in your model? (y/n) 
[y] > y
続いてバリデーションの設定をする。
Field: id
Type: integer
---------------------------------------------------------------
Please select one of the following validation options:
---------------------------------------------------------------
1 - alphanumeric
2 - between
3 - blank
4 - boolean
5 - cc
6 - comparison
7 - custom
8 - date
9 - decimal
10 - email
11 - equalto
12 - extension
13 - inlist
14 - ip
15 - maxlength
16 - minlength
17 - money
18 - multiple
19 - notempty
20 - numeric
21 - phone
22 - postal
23 - range
24 - ssn
25 - time
26 - url
27 - userdefined
28 - uuid
29 - Do not do any validation on this field.
... or enter in a valid regex validation string.
  
[29] > 
というように、カラム id について1から29までのルールが表示されるので、その中から適用するルールを選びます。 [] 内に表示されているのはcakephpが推測する値です。 一回選ぶ度に、
Would you like to add another validation rule? (y/n) 
[n] > 
と、追加のルールがあるかどうか聞いてくるので、ルールは複数選べます。 とりあえず、
id:
29
email:
7, 10, 19
password:
7, 19
type_id:
20
birthday:
8
img1:
29
img2:
29
created:
29
modified:
29
と、番号を選択して進みます。

Would you like to define model associations
(hasMany, hasOne, belongsTo, etc.)? (y/n) 
[y] > 
関連づけをするかどうかの確認です。YESです。
One moment while the associations are detected.
---------------------------------------------------------------
Please confirm the following associations:
---------------------------------------------------------------
Member belongsTo Type? (y/n) 
[y] > y
Member hasAndBelongsToMany Favorite? (y/n) 
[y] > y
Would you like to define some additional model associations? (y/n) 
[n] > n
とすると、
---------------------------------------------------------------
The following Model will be created:
---------------------------------------------------------------
Name:       Member
DB Table:   `members`
Validation: Array
(
    [email] => Array
        (
            [custom] => custom
            [email] => email
            [notempty] => notempty
        )

    [password] => Array
        (
            [custom] => custom
            [notempty] => notempty
        )

    [type_id] => Array
        (
            [numeric] => numeric
        )

    [birthday] => Array
        (
            [date] => date
        )

)

Associations:
 Member belongsTo Type
 Member hasAndBelongsToMany Favorite
---------------------------------------------------------------
Look okay? (y/n) 
[y] > 
とでるので、yesすると、
Baking model class for Member...

Creating file /Users/myname/Sites/cake/app/models/member.php
Wrote `/Users/myname/Sites/cake/app/models/member.php`
モデルが作られました。

最後にtestも作っておきます。

SimpleTest is not installed. Do you want to bake unit test files anyway? (y/n) 
[y] > y

You can download SimpleTest from http://simpletest.org

Baking test fixture for Member...

Creating file /Users/myname/Sites/cake/app/tests/fixtures/member_fixture.php
Wrote `/Users/myname/Sites/cake/app/tests/fixtures/member_fixture.php`
Bake is detecting possible fixtures..

Creating file /Users/myname/Sites/cake/app/tests/cases/models/member.test.php
Wrote `/Users/myname/Sites/cake/app/tests/cases/models/member.test.php`

作成された /app/models/member.php の中味はこんな感じです。

class Member extends AppModel {
 var $name = 'Member';
 var $displayField = 'email';
 var $validate = array(
  'email' => array(
   'custom' => array(
    'rule' => array('custom'),
    //'message' => 'Your custom message here',
    //'allowEmpty' => false,
    //'required' => false,
    //'last' => false, // Stop validation after this rule
    //'on' => 'create', // Limit validation to 'create' or 'update' operations
   ),
   'email' => array(
    'rule' => array('email'),
    //'message' => 'Your custom message here',
    //'allowEmpty' => false,
    //'required' => false,
    //'last' => false, // Stop validation after this rule
    //'on' => 'create', // Limit validation to 'create' or 'update' operations
   ),
   'notempty' => array(
    'rule' => array('notempty'),
    //'message' => 'Your custom message here',
    //'allowEmpty' => false,
    //'required' => false,
    //'last' => false, // Stop validation after this rule
    //'on' => 'create', // Limit validation to 'create' or 'update' operations
   ),
  ),
  'password' => array(
   'custom' => array(
    'rule' => array('custom'),
    //'message' => 'Your custom message here',
    //'allowEmpty' => false,
    //'required' => false,
    //'last' => false, // Stop validation after this rule
    //'on' => 'create', // Limit validation to 'create' or 'update' operations
   ),
   'notempty' => array(
    'rule' => array('notempty'),
    //'message' => 'Your custom message here',
    //'allowEmpty' => false,
    //'required' => false,
    //'last' => false, // Stop validation after this rule
    //'on' => 'create', // Limit validation to 'create' or 'update' operations
   ),
  ),
  'type_id' => array(
   'numeric' => array(
    'rule' => array('numeric'),
    //'message' => 'Your custom message here',
    //'allowEmpty' => false,
    //'required' => false,
    //'last' => false, // Stop validation after this rule
    //'on' => 'create', // Limit validation to 'create' or 'update' operations
   ),
  ),
  'birthday' => array(
   'date' => array(
    'rule' => array('date'),
    //'message' => 'Your custom message here',
    //'allowEmpty' => false,
    //'required' => false,
    //'last' => false, // Stop validation after this rule
    //'on' => 'create', // Limit validation to 'create' or 'update' operations
   ),
  ),
 );
 //The Associations below have been created with all possible keys, those that are not needed can be removed

 var $belongsTo = array(
  'Type' => array(
   'className' => 'Type',
   'foreignKey' => 'type_id',
   'conditions' => '',
   'fields' => '',
   'order' => ''
  )
 );

 var $hasAndBelongsToMany = array(
  'Favorite' => array(
   'className' => 'Favorite',
   'joinTable' => 'members_favorites',
   'foreignKey' => 'member_id',
   'associationForeignKey' => 'favorite_id',
   'unique' => true,
   'conditions' => '',
   'fields' => '',
   'order' => '',
   'limit' => '',
   'offset' => '',
   'finderQuery' => '',
   'deleteQuery' => '',
   'insertQuery' => ''
  )
 );

}
よさそうな感じですね。

あとは同様にusersテーブルについても作っておきます。関連づけはなしですね。

class User extends AppModel {
 var $name = 'User';
 var $displayField = 'name';
 var $validate = array(
  'username' => array(
   'notempty' => array(
    'rule' => array('notempty'),
    //'message' => 'Your custom message here',
    //'allowEmpty' => false,
    //'required' => false,
    //'last' => false, // Stop validation after this rule
    //'on' => 'create', // Limit validation to 'create' or 'update' operations
   ),
  ),
  'password' => array(
   'notempty' => array(
    'rule' => array('notempty'),
    //'message' => 'Your custom message here',
    //'allowEmpty' => false,
    //'required' => false,
    //'last' => false, // Stop validation after this rule
    //'on' => 'create', // Limit validation to 'create' or 'update' operations
   ),
  ),
 );
}


CakePHP1.3で作る会員管理システム(4) schemaを作る

schemaを作る

ここでついでなので schema を作っておきます。 自分は今 app フォルダーの中にいるので、そのまま

cake schema generate -f
と打ちます。
Welcome to CakePHP v1.3.11 Console
---------------------------------------------------------------
App : app
Path: /Users/myname/Sites/cake/app
---------------------------------------------------------------
Cake Schema Shell
---------------------------------------------------------------
Generating Schema...
Schema file: schema.php generated
とメッセージが出て終了。

/app/config/schema/schema.php というファイルが生成されます。 中味はこんな感じ。

class AppSchema extends CakeSchema {
 var $name = 'App';

 function before($event = array()) {
  return true;
 }

 function after($event = array()) {
 }

 var $favorites = array(
  'id' => array('type' => 'integer', 'null' => false, 'default' => NULL, 'key' => 'primary'),
  'name' => array('type' => 'string', 'null' => false, 'default' => NULL, 'length' => 100, 'collate' => 'utf8_general_ci', 'charset' => 'utf8'),
  'indexes' => array('PRIMARY' => array('column' => 'id', 'unique' => 1)),
  'tableParameters' => array('charset' => 'utf8', 'collate' => 'utf8_general_ci', 'engine' => 'MyISAM')
 );
 var $members = array(
  'id' => array('type' => 'integer', 'null' => false, 'default' => NULL, 'key' => 'primary'),
  'email' => array('type' => 'string', 'null' => false, 'default' => NULL, 'length' => 100, 'collate' => 'utf8_general_ci', 'charset' => 'utf8'),
  'password' => array('type' => 'string', 'null' => false, 'default' => NULL, 'length' => 100, 'collate' => 'utf8_general_ci', 'charset' => 'utf8'),
  'type_id' => array('type' => 'integer', 'null' => false, 'default' => NULL, 'key' => 'index'),
  'birthday' => array('type' => 'date', 'null' => true, 'default' => NULL),
  'img1' => array('type' => 'string', 'null' => true, 'default' => NULL, 'collate' => 'utf8_general_ci', 'charset' => 'utf8'),
  'img2' => array('type' => 'string', 'null' => true, 'default' => NULL, 'collate' => 'utf8_general_ci', 'charset' => 'utf8'),
  'created' => array('type' => 'datetime', 'null' => true, 'default' => NULL),
  'modified' => array('type' => 'datetime', 'null' => true, 'default' => NULL),
  'indexes' => array('PRIMARY' => array('column' => 'id', 'unique' => 1), 'type_id' => array('column' => 'type_id', 'unique' => 0)),
  'tableParameters' => array('charset' => 'utf8', 'collate' => 'utf8_general_ci', 'engine' => 'MyISAM')
 );
 var $members_favorites = array(
  'id' => array('type' => 'integer', 'null' => false, 'default' => NULL, 'key' => 'primary'),
  'member_id' => array('type' => 'integer', 'null' => false, 'default' => NULL, 'key' => 'index'),
  'favorite_id' => array('type' => 'integer', 'null' => false, 'default' => NULL, 'key' => 'index'),
  'indexes' => array('PRIMARY' => array('column' => 'id', 'unique' => 1), 'member_id' => array('column' => 'member_id', 'unique' => 0), 'favorite_id' => array('column' => 'favorite_id', 'unique' => 0)),
  'tableParameters' => array('charset' => 'utf8', 'collate' => 'utf8_general_ci', 'engine' => 'MyISAM')
 );
 var $types = array(
  'id' => array('type' => 'integer', 'null' => false, 'default' => NULL, 'key' => 'primary'),
  'name' => array('type' => 'string', 'null' => false, 'default' => NULL, 'length' => 100, 'collate' => 'utf8_general_ci', 'charset' => 'utf8'),
  'indexes' => array('PRIMARY' => array('column' => 'id', 'unique' => 1)),
  'tableParameters' => array('charset' => 'utf8', 'collate' => 'utf8_general_ci', 'engine' => 'MyISAM')
 );
 var $users = array(
  'id' => array('type' => 'integer', 'null' => false, 'default' => NULL, 'key' => 'primary'),
  'username' => array('type' => 'string', 'null' => false, 'default' => NULL, 'length' => 100, 'collate' => 'utf8_general_ci', 'charset' => 'utf8'),
  'password' => array('type' => 'string', 'null' => false, 'default' => NULL, 'length' => 100, 'collate' => 'utf8_general_ci', 'charset' => 'utf8'),
  'name' => array('type' => 'string', 'null' => true, 'default' => NULL, 'length' => 100, 'collate' => 'utf8_general_ci', 'charset' => 'utf8'),
  'email' => array('type' => 'string', 'null' => true, 'default' => NULL, 'length' => 100, 'collate' => 'utf8_general_ci', 'charset' => 'utf8'),
  'indexes' => array('PRIMARY' => array('column' => 'id', 'unique' => 1)),
  'tableParameters' => array('charset' => 'utf8', 'collate' => 'utf8_general_ci', 'engine' => 'MyISAM')
 );
}
これを作っておけば、環境が変わって、データベースがMySQLからPostgreSQLに変わったりしても、すぐにデータベースを構築できます。

その場合は、

cake schema create
と打ちます。

例えばこいつをPostgreSQLの環境で構築したデータベースはこうなりました。

cake_db=# ¥d
                    List of relations
 Schema |           Name           |   Type   |  Owner
--------+--------------------------+----------+----------
 public | favorites                | table    | postgres
 public | favorites_id_seq         | sequence | postgres
 public | members                  | table    | postgres
 public | members_favorites        | table    | postgres
 public | members_favorites_id_seq | sequence | postgres
 public | members_id_seq           | sequence | postgres
 public | types                    | table    | postgres
 public | types_id_seq             | sequence | postgres
 public | users                    | table    | postgres
 public | users_id_seq             | sequence | postgres
(10 rows)

cake_db=# ¥d users
                                  Table "public.users"
  Column  |          Type          |                     Modifiers

----------+------------------------+----------------------------------------------------
 id       | integer                | not null default nextval('users_id_seq'::regclass)
 username | character varying(100) | not null
 password | character varying(100) | not null
 name     | character varying(100) | default NULL::character varying
 email    | character varying(100) | default NULL::character varying
Indexes:
    "users_pkey" PRIMARY KEY, btree (id)

cake_db=# ¥d members
                                    Table "public.members"
  Column  |            Type             |                      Modifiers
----------+-----------------------------+------------------------------------------------------
 id       | integer                     | not null default nextval('members_id_seq'::regclass)
 email    | character varying(100)      | not null
 password | character varying(100)      | not null
 type_id  | integer                     | not null
 birthday | date                        |
 img1     | character varying(255)      | default NULL::character varying
 img2     | character varying(255)      | default NULL::character varying
 created  | timestamp without time zone | not null
 modified | timestamp without time zone | not null
Indexes:
    "members_pkey" PRIMARY KEY, btree (id)
    "type_id" btree (type_id)

cake_db=# ¥d favorites
                                 Table "public.favorites"
 Column |          Type          |                       Modifiers
--------+------------------------+--------------------------------------------------------
 id     | integer                | not null default nextval('favorites_id_seq'::regclass)
 name   | character varying(100) | not null
Indexes:
    "favorites_pkey" PRIMARY KEY, btree (id)

cake_db=# ¥d types
                                 Table "public.types"
 Column |          Type          |                     Modifiers
--------+------------------------+----------------------------------------------------
 id     | integer                | not null default nextval('types_id_seq'::regclass)
 name   | character varying(100) | not null
Indexes:
    "types_pkey" PRIMARY KEY, btree (id)

cake_db=# ¥d members_favorites
                            Table "public.members_favorites"
   Column    |  Type   |                           Modifiers
-------------+---------+----------------------------------------------------------------
 id          | integer | not null default nextval('members_favorites_id_seq'::regclass)
 member_id   | integer | not null
 favorite_id | integer | not null
Indexes:
    "members_favorites_pkey" PRIMARY KEY, btree (id)
    "favorite_id" btree (favorite_id)
    "member_id" btree (member_id)

MySQL からPostgreSQL へデータベースが変わるなんてことはないかもしれないし、後でやっても構わない訳ですが、作っておけば後々便利ということでせっかく今ターミナルを開いてる訳ですから schema だけは作っておいて損はないだろうと思います。
データベースは MySQL のままでも、開発用環境を移す時にコマンド一発でデータベースを作れてしまうのでとても楽ですね。

ちなみに、

cake schema create
の実行は、まず既存のテーブルを削除してから、新規にテーブルを作成する、という処理になるので、テーブルが存在していないのに、「削除しますか?」 で「はい」と返事すると、だーっとエラーが出ます。 が、特に問題はありません。
Welcome to CakePHP v1.3.11 Console
---------------------------------------------------------------
App : app
Path: /Users/myname/Sites/cake/app
---------------------------------------------------------------
Cake Schema Shell
---------------------------------------------------------------

The following table(s) will be dropped.
favorites
members
members_favorites
types
users
Are you sure you want to drop the table(s)? (y/n) 
[n] > y
Dropping table(s).

ここでWarning発生!

The following table(s) will be created.
favorites
members
members_favorites
types
users
Are you sure you want to create the table(s)? (y/n) 
[y] > 
Creating table(s).
favorites updated.
members updated.
members_favorites updated.
types updated.
users updated.
End create.

CakePHP1.3で作る会員管理システム(3) データベース接続

データベース接続

データベースに接続するための設定を行います。
設定ファイルは /app/config/database.php.default を書き換えて、/app/config/database.php にリネームするだけなので、エディターで開いて編集すればいいのですが、ここでは console の cake コマンドを使ってやってみます。
大元の /cake/console の中にあるのがcakeコマンドです。
自分のhomeディレクトリから、

cd Sites/cake/cake/console
./cake
と打てば
Welcome to CakePHP v1.3.11 Console
---------------------------------------------------------------
Current Paths:
 -app: app
 -working: /Users/myname/Sites/cake/app
 -root: /Users/myname/Sites/cake
 -core: /Users/myname/Sites/cake

Changing Paths:
your working path should be the same as your application path
to change your path use the '-app' param.
Example: -app relative/path/to/myapp or -app /absolute/path/to/myapp

Available Shells:
 acl [CORE]                             i18n [CORE]                            
 api [CORE]                             schema [CORE]                          
 bake [CORE]                            testsuite [CORE]                       
 console [CORE]                         

To run a command, type 'cake shell_name [args]'
To get help on a specific command, type 'cake shell_name help'
と表示され、とりあえず動くのが分かります。

で、一応このcakeコマンドにパスを通しておきます。

vim .profile
としてvim エディターを起動し、
export PATH=/Users/myname/Sites/cake/cake/console:$PATH
の一行を追加します。
ターミナルに戻って、
. .profile
して、
printenv PATH
で、パスを確認します。
/Users/myname/Sites/cake/cake/console:
と入っていればOK.

基本、自分の app フォルダーの中で作業するのがいいです。

cd Sites/cake/app
cake bake
別の場所にいる場合は、 app の場所を指定します。今自分がhomeにいるんだったら、
cake -app Sites/cake/app bake
とすると、
Welcome to CakePHP v1.3.11 Console
---------------------------------------------------------------
App : app
Path: /Users/myname/Sites/cake/app
---------------------------------------------------------------
Your database configuration was not found. Take a moment to create one.
---------------------------------------------------------------
Database Configuration:
---------------------------------------------------------------
Name:  
[default] > 
というように対話式の設定画面になりますので、必要な項目を入力します。
---------------------------------------------------------------
The following database configuration will be created:
---------------------------------------------------------------
Name:         default
Driver:       mysql
Persistent:   false
Host:         localhost
User:         cake_user
Pass:         ********
Database:     cake_db
Encoding:     utf8
---------------------------------------------------------------
という感じに、データベースの設定を入れて[y]すると、自動で /app/config/database.php が作られます。

ブラウザで http://localhost/~myname/cake/ を開いてみると

Your database configuration file is present.
Cake is able to connect to the database.
と出てるはずです。


CakePHP1.3で作る会員管理システム(2) CakePHPの設置

CakePHPの設置

本家サイトからダウンロードした CakePHP を設置します。
「Download」の画像をクリックするとgithub のページに飛ぶので、そちらから、 1.3.11.zip — 1.3.11 をクリックします。

ダウンロードしたファイルを解凍すると、 cakephp-cakephp-3b830a4 という名前のフォルダーが出来るので、これを cake とリネームしてローカル環境のドキュメントルート以下にコピーします。
MacOSXの場合は、いわゆる「サイト」フォルダー

/Users/myname/Sites
以下ということになります。

Windows の場合は、apache をどこにインストールしたかにもよるんでしょうが、その htdocs 以下、ということです。例えば、

c:¥Program Files¥apache・・・・¥htdocs
になるかと思います。
本番リリースと同じ構造にしておく、という手もありますが、開発用のローカル環境ではなにもいじらない方がやりやすいんじゃないですかね。
なにしろ、まっさらの状態でも本体をダウンロードしてきてそのまま始められる訳ですから。

で、 http://localhost/~myname/cake/ をブラウザから開きます。

Warning (512): /Users/myname/Sites/cake/app/tmp/cache/ is not writable [CORE/cake/libs/cache/file.php, line 267]
Warning (512): /Users/myname/Sites/cake/app/tmp/cache/persistent/ is not writable [CORE/cake/libs/cache/file.php, line 267]
Warning (512): /Users/myname/Sites/cake/app/tmp/cache/models/ is not writable [CORE/cake/libs/cache/file.php, line 267]
Notice (1024): Please change the value of 'Security.salt' in app/config/core.php to a salt value specific to your application [CORE/cake/libs/debugger.php, line 694]
Notice (1024): Please change the value of 'Security.cipherSeed' in app/config/core.php to a numeric (digits only) seed value specific to your application [CORE/cake/libs/debugger.php, line 698]
という3つの Warning と2つの Notice が出ますが、とりあえず動いてるってことでOKでしょう。

一つ一つ対応していきます。

/app/tmp/cache を書き込み可能にします。
ついでに /app/tmp も書き込み可能にするので、/appに移動して、

chmod -R 0777 tmp
とします。 ブラウザをリロードします。

引き続き、/app/config/core.php を開いて、

 Configure::write('Security.salt', 'DYhG93b0qyJfIxfs2guVoUubWwvniR2G0FgaC9mi');
 Configure::write('Security.cipherSeed', '76859309657453542496749683645');
の2つの部分の値を書き換えます。

これでOKのはずですが、もし、php が 5.3 で、しかも php.ini に default timezone の設定をしていなかったりすると、

Warning (2): strtotime() [function.strtotime]: It is not safe to rely on the system's timezone settings. You are *required* to use the date.timezone setting or the date_default_timezone_set() function. In case you used any of those methods and you are still getting this warning, you most likely misspelled the timezone identifier. We selected 'Asia/Tokyo' for 'JST/9.0/no DST' instead [CORE/cake/libs/cache.php, line 597]
というような激しいエラーが出ますので、その場合は、 /app/config/core.php の、
 //date_default_timezone_set('UTC');
となっているところを、
 date_default_timezone_set('Asia/Tokyo');
としておきます。
できれば php.ini の方を設定することをおすすめします。

最後、ついでなので、以下の一行のコメントアウトを外しておきます。

 //Configure::write('Routing.prefixes', array('admin'));


CakePHP1.3で作る会員管理システム(1) データベースの作成

データベースの作成

いろんなやり方があるとは思いますが、まずはデータベースを作っておくのがいいと思います。
今回はMySQLで作りました。

CREATE DATABASE cake_db CHARACTER SET utf8;
GRANT all ON cake_db.* TO cake_user@localhost IDENTIFIED BY 'password';

users は管理側の管理者アカウントです。
管理側はAuthコンポーネントを使って認証するので、テーブル名を users にしておきます。
他の名前でも可能ですが、users が Auth コンポーネントのデフォルトなのでそうしておいた方が面倒がなくてよいです。

CREATE TABLE users (
 id INT(11) AUTO_INCREMENT,
 username VARCHAR(100) NOT NULL,
 password VARCHAR(100) NOT NULL,
 name VARCHAR(100),
 email VARCHAR(100),
 PRIMARY KEY (id)
);

membersは会員の情報を入れるテーブルです。
本当はここにstatusフィールドを入れて、仮登録・本登録の処理を入れたかったのですが、今回は見送りました。

CREATE TABLE members (
 id int(11) AUTO_INCREMENT,
 email VARCHAR(100) NOT NULL,
 password VARCHAR(100) NOT NULL,
 type_id INT(11) NOT NULL,
 birthday DATE,
 img1 VARCHAR(255),
 img2 VARCHAR(255),
 created DATETIME,
 modified DATETIME,
 PRIMARY KEY (id),
 KEY type_id (type_id)
);

typesは会員種別のマスターです。
一般会員、とか特別会員、とかのデータを入れます。

CREATE TABLE types (
 id int(11) AUTO_INCREMENT,
 name VARCHAR(100) NOT NULL,
 PRIMARY KEY (id)
);

favoritesは会員の「好きな物」の選択値を入れます。
「好きな物」でも「趣味」でも何でもいいんですが、要は複数選択の場合の処理を入れたいのです。

CREATE TABLE favorites (
 id int(11) AUTO_INCREMENT,
 name VARCHAR(100) NOT NULL,
 PRIMARY KEY (id)
);

members_favorites は会員情報と好きな物を関連づけるためのテーブルです。
多対多の関係になるのでいわゆる HABTM の連結になります。

CREATE TABLE members_favorites (
 id int(11) AUTO_INCREMENT,
 member_id INT(11) NOT NULL,
 favorite_id INT(11) NOT NULL,
 PRIMARY KEY (id),
 KEY member_id (member_id),
 KEY favorite_id (favorite_id)
);

2011-09-03

OGタグ用のサムネイル

テスト
インゲン

OSX で MacPorts を使って、CoffeeScript を試してみる

WEB+DB PRESS Vol.64 の記事で面白そうだったので早速試してみた。
記事では CoffeeScript のコンパイラをインストールするのに、まず Node.js と npm が必要とあり、
その Node.js のインストールには nvm を使ってみる、とあるが、面倒なので port でやってみる。
$ port search node*
とすると、以下の4つが見つかるので、
nodejs @0.4.11 (devel, net)
    Evented I/O for V8 JavaScript

nodejs-devel @0.5.4 (devel, net)
    Evented I/O for V8 JavaScript

nodejuice @1.5.0 (www)
    A web development tool to autorefesh the browser on changes.

npm @1.0.26 (devel)
    node package manager

Found 4 ports.
$ sudo port install nodejs
$ sudo port install npm
でよさそうだ。
が、
$ port search coffee*
とすると、
coffee-script @1.1.2 (lang)
    a language that compiles into JavaScript
こう出るので、もしかすると
$ sudo port install coffee-script
だけでもよかったのかもしれない。いずれにしろ、これで
$ coffee -v
CoffeeScript version 1.1.2
というように入ったので、記事の通りに
hello = ->
  console.log "Hello, World!"

hello()
を hello.coffee として保存し、

コンパイル。
$ coffee -c hello.coffee 
Node.js から実行。
$ node hello.js
Hello, World!
CoffeeScript から直接実行。
$ coffee hello.coffee 
Hello, World!
生成された js ファイルは、
(function() {
  var hello;
  hello = function() {
    return console.log("Hello, World!");
  };
  hello();
}).call(this);
となっている。
うまくいったようだ。
WEB+DB PRESS Vol.64

このブログを検索

Powered by Blogger.

ラベル

php (17) jQuery (13) OSX (10) MySQL (8) Javascript (7) Postgres (7) port (7) apache (6) Java (3) Smarty (2) html (2) pear (2) FCKEditor (1) XAMPP (1) css (1) git (1) perl (1) ruby (1)

Facebookバナー