Cakephp
Published: 13:12, Thursday 14 July 2011
Notes
What's this? See my article about Notes.
View as plain text file.
conventions:
filenames_underscored, ClassnamesCamelcased
MyHandyComponent -> my_handy.php
model:
classnames singular
tables plural underscored
inflector finds singular/plural
fields underscored
join tables alphabetical
controller:
plural, camelcased
index() is default
urls:
ApplesController
example.com/apples
/redApples /RedApples /Red_apples /red_apples -> RedApplesController
view:
template files:
PeopleController getReady()
/app/views/people/get_ready.ctp
example:
database table: people
model class: Person in /app/models/person.php
controller class: PeopleController in /app/controllers/people_controller.php
view template: /app/views/people/index.ctp
configuration:
database: copy app/config/database.php.default and configure
core.php
debug=0,1,2
configuration class
call: Configure::read('debug'); read()
write('var','val') dot notation makes array
delete
load(file)
contains $config array
version
add/import classes:
App::import(type,name,parent,search,file,return)
core libs: import('Core', 'Sanitize');
analogous for controllers, models, components, behaviors, views, helpers
from plugins: import(type,'PluginName.Name')
vendors
import('Vendor', 'geshi'), import('Vendor', 'flickr/flickr');
import('Vendor','SomeName',array('file' => 'services'.DS.'some.name.php'))
blog tutorial:
config db
in app/config/core.php 203, 208
configure salt for hashes
configure seed for encryption
make tmp writable
echo `whoami` and change ownership of tmp to that user
chown -R.www-data app/tmp
activate mod_rewrite
post:
index:
model:
app/models/post.php
class Post extends AppModel { var $name = 'Post'; }
controller:
app/controllers/posts_controller.php
class PostsController extends AppController {
var $helpers = array('Html','Form');
var $name = 'Posts';
function index() {
$this->set('posts', $this->Post->find('all'));
}
}
view:
app/views/posts/index.ctp
$posts = array(array("Post" => array("id" => 1, ...
can use in index.ctp
$this->Html->link(caption,params)
view:
parameter $id = null
$this->Post->id = $id;
$this->set('post', $this->Post->read());
.../view.ctp
$post = array('Post' => array('id' => ...
add:
post information: $this->data
$this->Post->save($this->data) returns 1 if successful
$this->Session->setFlash('message');
$this->redirect(params)
.../add.ctp
$this->Form->create(name) -> NameControllerForm
input(name,params)
end(submit value)
validation:
in the model
$validate = array(field => array('rule' => 'notEmpty'
delete:
$this->Post->delete($id)
again setFlash and redirect
no need for *.ctp
edit:
again read, save, setFlash, redirect
save assumes you're editing a model if id is present
in template:
Form->create,input
values are populated
routing:
blog:
config/routes.php
default root:
Router::connect('/',
array('controller' => 'pages', 'action' => 'display', 'home'));
replace with:
Router::connect('/',
array('controller' => 'posts', 'action' => 'index')))
default
controller/action/param1/param2/param3
passed as arguments on the method called: view($id)
$this->params['pass'] as an array
$this>passedArgs
more routing info
installation:
development: just put it where needed!
production:
install cake where you want (cakedir)
cakedir/app/webroot shall be DocumentRoot! in apache config
advanced:
put cake, app, webroot where you want them
modify webroot/index.php (and webroot/test.php)
ROOT: path to app
APP_DIR: name of app
CAKE_CORE_INCLUDE_PATH: path to cake
(use DS)
additonal class paths (share classes between systems)
bootstrap.php, App::build(array(
'plugins' => array(path, nextpath),
...
utility: pr() debug()
inflection:
config/bootstrap.php
Inflector::rules('singular', array(
'rules' => array(from => to,...
'uninflected' => array
'irregular' => array
Inflector::rules('plural', array
additional config
bootstrap.php
for convenience functions, global constans, additional model, view, paths
controllers:
logic for single model
actions
attributes:
$name = 'Recipes'
$uses = array('Recipe', 'User');
$helpers = array('Ajax');
$layout = sth in views/layouts or default.ctp or capephp's default
$params
['forms'] post data from forms and $_FILES
admin: 1 if admin routing
bare: 1 if empty layout
isAjax: if ajax call
controller: name of controller
action: action
pass: url parameters
url: requested url including key-value pairs
data: post data from form helper
prefix: routing prefix
named: key:value pairs
methods:
set(var,val) for views
render() performs view logic, automatically called, for alternate views
redirect(url,status,exit)
flash(message,url,pause,layout) shows a message before
beforeFilter: before all actions
beforeRender: after action, before rendering
afterFilter: after rendering
scaffolding ones
constructClasses: loads model, called auto
referer, disableCache, postConditions, paginate
requestAction(url,options) e.g. array('return') rarely appropriate
loadModel(modelClass, id)
components:
shared between controllers
security, session, access, email, cookies, auth, request handling
configure: beforeFilter or $components array
create: controllers/components/..
extends Object ?
callbacks:
initialize(controller,settings), startup(controller),
beforeRender(controller) shutdown(controller), beforeRedirect(controller)
models:
associated
data type associations:
primary_key: NOT NULL auto_increment
string: varchar(255)
text: text
integer: int(11)
float: float
datetime: datetime
timestamp: datetime
time: time
date: date
binary: blob
boolean: tinyint(1)
special fields:
title or else name field or else $displayField used as label
created,modified datetime will be modified by cakephp
primary key, else UUIDs designed to be unique across tables and databases
retrieving:
find(type,params)
params:
conditions, recursive, fields, order, group, limit, page, offset,
callbacks
type:
first, count, all, list (indexed array, threaded, neighbors
magic: findAllBy<fieldName>, findBy<>
query returns an array
field, read, complex WHERE conds and subqueries
saving:
create()
set(var,val)
save(array(modelName => array( fieldname => value
saveField
updateAll(fields,conditions)
saveAll
delete:
delete(id,cascade)
deleteAll(conditions,cascade,callbacks)
associations:
relational mapping
variable, just model name or array with
className, foreignKey, conditions, fields, order, dependent
type (of join), counterCache, counterScope
limit, offset, exclusive, finderQuery
joinTable, with, associationForeignKey, unique, finderQuery,
deleteQuery, insertQuery
one to one
hasOne
the other model contains foreign key school_id
find() returns array(this => array(...), other => array())
one to many
hasMany
the other contains the foreign key
many to one
belongsTo
the current model contains the foreign key
many to many
hasAndBelongsToMany
requires separate join table with both model names in alphabetical order
to the same model: use foreignKey and keys in array to identify
cake creates links between associated models
callback methods
model attributes
additional methods
virtual fields
transactions
behaviors
datasources
views
helpers
scaffolding
console
plugins:
bundle of controllers, models and views
global
common tasks:
data validation
data sanitization
error handline
debugging
caching
logging
testing
internationalization & localization
pagination
rest
core components
access control lists (acl)
authentication
cookies
email
request handling
security component
sessions
core behaviors
acl
containable
translate
tree
core helpers
ajax
cache
form
html
js
javascript
number
paginator
rss
session
text
time
xml
core utility libraries
app
inflector
string
xml
set
security
cache
httpsocket
router
core console applications
code generation (bake)
schema management, migrations
modify default html
deployment
Write a Comment
* These fields are mandatory.