Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Added example and some doc for CakeSchema callbacks #249

Merged
merged 4 commits into from Apr 23, 2012
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
50 changes: 50 additions & 0 deletions en/console-and-shells/schema-management-and-migrations.rst
Expand Up @@ -41,6 +41,56 @@ Where filename.sql is the desired filename for the sql dump. If you
omit filename.sql the sql dump will be output to the console but omit filename.sql the sql dump will be output to the console but
not written to a file. not written to a file.


CakeSchema callbacks
====================

After generating a schema you might want to insert data on some
tables to get your app started. This can be achieved through
CakeSchema callbacks. Every schema file is generated with a
``before($event = array())`` and a ``after($event = array())`` method.

The ``$event`` param holds an array with two keys. One to tell if a
table is being dropped or created and another for errors. Examples::

array('drop' => 'posts', 'errors' => null)
array('create' => 'posts', 'errors' => null)

Adding data to a posts table for example would like this::

<?php
App::uses('Post', 'Model');
public function after($event = array()) {
if(isset($event['create'])){
switch($event['create']){
case 'posts':
$post = ClassRegistry::init('Post');
$post->create();
$post->save(
array('Post' =>
array('title' => 'CakePHP Schema Files')
)
);
break;
}
}
}

The ``before()`` and ``after()`` callbacks run each time a table is created
or dropped on the current schema.

When inserting data to more than one table you'll need to flush the database
cache after each table is created. Cache can be disable by setting
``$db->cacheSources = false`` in the before action(). ::

<?php
public $connection = 'default';

public function before($event = array()) {
$db = ConnectionManager::getDataSource($this->connection);
$db->cacheSources = false;
return true;
}

Migrations with CakePHP schema shell Migrations with CakePHP schema shell
==================================== ====================================


Expand Down