Вы находитесь на странице: 1из 10

Instalar o framework cakephp no Ubuntu pelos repositrios

sudo apt-get install cakephp-scripts


Executando o gerador de cdigo bake:
cake bake /path/completo/app
9.1 Code Generation with Bake
* Edit
* Comments (2)
* History
Youve already learned about scaffolding in CakePHP: a simple way to get up and ru
nning with only a database and some bare classes. CakePHPs Bake console is anothe
r effort to get you up and running in CakePHP fast. The Bake console can create
any of CakePHPs basic ingredients: models, views and controllers. And we arent jus
t talking skeleton classes: Bake can create a fully functional application in ju
st a few minutes. In fact, Bake is a natural step to take once an application ha
s been scaffolded.
To use Bake, you ll need to run the cake script located in the /cake/console/ fo
lder.

$ cd ./cake/console/
$ cake bake
Depending on the configuration of your setup, you may have to set execute rights
on the cake bash script or call it using ./cake bake. The cake console is run u
sing the PHP CLI (command line interface). If you have problems running the scri
pt, ensure that you have the PHP CLI installed and that it has the proper module
s enabled (eg: MySQL).
When running Bake for the first time, you ll be prompted to create a Database Co
nfiguration file, if you haven t created one already.

After you ve created a Database Configuration file, running Bake will present yo
u with the following options:

--------------------------------------------------------------App : app
Path: /path-to/project/app
--------------------------------------------------------------Interactive Bake Shell
--------------------------------------------------------------[D]atabase Configuration
[M]odel
[V]iew
[C]ontroller
[P]roject
[Q]uit
What would you like to Bake? (D/M/V/C/P/Q)
>
Alternatively, you can run any of these commands directly from the command line:
$ cake bake db_config
$ cake bake model
$ cake bake view

$ cake bake controller


$ cake bake project
Configuraes do CakePHP
Debug:
app/config/core.php
Configure::write( debug , 2);

Configure::write( App.encoding , UTF-8 );

define( LOG_ERROR , 2);

Configure::write( Security.level , high );

Configure::write( Security.salt , DYhG93b0qyJfIxfs2guVoUubWwvniR2G0FgaC9mi );

Cake Hot Features


# Model, View, Controller Architecture
# Application Scaffolding
# Code generation via Bake
# Helpers for HTML, Forms, Pagination, AJAX, Javascript, XML, RSS and more
# Access Control Lists and Authentication
# Simple yet extensive validation of model data
# Router for mapping urls and handling extensions
# Security, Session, and RequestHandler Components
# Utility classes for working with Files, Folders, Arrays and more

CakePHP: apenas um core para diversos aplicativos


Agora que eu me mudei pro DreamHost, estou querendo migrar e fazer diversos site
s dentro do espao que tenho por aqui. A maioria dos sites que fao atualmente so des
envolvidos com o framework CakePHP, ento eu configurei um novo domnio, abri a past
a que foi criada e mandei o cake todo pra l. A minha estrutura de diretrios ficou
mais ou menos assim:
/
/eberfdias.com
/app
/webrooot
index.php
/cake
/etc...
Como vocs podem ver, o core do cake esta dentro da pasta onde coloquei meu aplica
tivo tambm, na pasta do domnio que registrei por l. O core do cake tem quase 4Mb e
se eu fosse dar upload do core toda vez que eu quisesse criar um novo aplicativo
baseado em CakePHP, alm de ser um saco, seria uma duplicao de arquivos desnecessria
[a no ser que voc tenha feito mudanas especficas no core pra suprir as necessidades
de um determinado servio].
Mas por que desnecessrio? Porque voc pode colocar o core do cake fora da pasta do
seu domnio, tornando-o acessvel para qualquer aplicao em qualquer outra pasta. Fazer
isso muito simples [principalmente porque a forma como eu fiz foi extremamente
simplista].

O primeiro passo transferir a pasta cake de dentro da basta do domnio para o seu ro
ot. A estrutura de diretrios fica assim com esta mudana:
/
/cake
/eberfdias.com
/app
/webroot
index.php
/etc...
Depois disto, basta configurar o arquivo index.php na sua pasta webroot, dentro
da pasta app [se este mesmo o nome que voc deu]. A nica linha que voc modifica esta
:
define( CAKE_CORE_INCLUDE_PATH , ROOT);

trocando por:
define( CAKE_CORE_INCLUDE_PATH , dirname(dirname(dirname(dirname(__FILE__)))));

O comando dirname pega o diretrio do arquivo em questo, mesmo se ele for um arquiv
o incluso, ou seja, ele pega a pasta do arquivo incluido, no do arquivo que o est
incluindo. Sendo assim, ns retornamos 4 nveis para encontrarmos a pasta cake. Uma fe
z feito isso, o seu aplicativo dever funcionar normalmente acessando o core do ca
ke fora da pasta do domnio!
Se voc usa windows pra desenvover seus sites [como eu], voc tambm pode mover a past
a cake pra fora da pasta do seu aplicativo com essas configuraes. Assim, se voc des
envolve varios sites com Cake, voc pode manter apenas um core pra todos eles. A a
tualizao do core tmb se torna mais simples desta forma!
O mais legal que o CakePHP deixa voc customizar o local de todos os pedaos do seu ap
licativo, possibilitando o aumento da segurana de seu cdigo longe do alcance dos u
surios. Para saber mais sobre isso s dar uma olhadinha neste captulo do manual do C
akePHP.
Fonte: http://www.eberfdias.com/blog/2008/01/17/cakephp-apenas-um-core-para-dive
rsos-aplicativos/
Usando o Scaffold
CakePHP: Using scaffolding for rapid application building
ScaffoldingThats right, Im still on my CakePHP journey. Ive been spending quite a b
it of time now trying to match what I want to build with how to go about doing i
t in CakePHP. We all know that the blog example is pretty simplistic - a real wo
rld app wont be quite so straightforward. At the moment, Im trying to build up an
intranet of sorts, with lots of different independant apps, and its driving me cr
azy How would I structure the it? Should I use plugins? The folders, the views etc.
Yes, its all still a big mess.
In any case, I found that CakePHP has a really nifty feature that really helps w
ith sorting out the mess, and its called scaffolding.

Scaffolding is Cakes way of quickly building up a basic application that can Creat
e, Retrieve, Update and Delete (or CRUD) objects, with just a few simple lines of code
All we need to do is to setup your database table, the model and the controller,
and thats it - you can browse your database, add new entries, delete, update etc

. All the basic CRUD functionality you need.


Following on from my last posting on associations, lets add in Authors to our blog
application.
Create the authors database table
First thing we should do is to create a table called authors with a primary key id
and a name field, and insert one sample row.
1
2
3
4
5
6

CREATE TABLE authors (


id INT( 10 ) UNSIGNED NOT NULL AUTO_INCREMENT ,
name TEXT NOT NULL ,
PRIMARY KEY ( id )
);
INSERT INTO comments ( id , name ) VALUES ( NULL , Jeremy Clarkson );

Create an Author model


Next, we should create our model at this location /app/models/author.php with so
mething like this:
1
2
3
4
5
6

<?php
class Author extends AppModel
{
var $name = Author ;
}
?>

Create the controller with scaffolding


Now, we can go ahead to create the controller at this location /app/controllers/
authors_controller.php. But this controller is going to be different from our pr
evious examples. It will only contain 1 line within the AuthorsController class:
1
2
3
4
5
6

<?php

class AuthorsController extends AppController


{
var $scaffold;
}
?>
Scaffolding in action!
Once you have done the above, point your browser to your authors url. In my case
, its http://localhost/authors, and what I see is a table listing with 1 entry Jeremy Clarkson.
CakePHP scaffolding
Thats it. You can now perform all the basic CRUD actions, all from 1 line of var
$scaffold;.
A word of warning
Cakes documentation has made it very clear that scaffolding is not a production s
olution. Its just a quick way for you to do some prototyping. Once you have your
prototype, you should be able to be able to swap out the scaffold with your own
code, as your codes will take precedence over the ones from the scaffold.
Im going to end the posting here, even thought we should, by right, link up the a
uthors and posts table using Associations. If you have read my previous CakePHP
post, you should know how to go about doing that.
Share and Enjoy: These icons link to social bookmarking sites where readers can
share and discover new web pages.
Fonte: http://www.askaboutphp.com/tutorials/33/cakephp-using-scaffolding.html
Scaffolding (Prottipos)
Introduo

Scaffold (equivalente em portugus seria andaime, aqui trataremos como prottipo) de


aplicao uma tcnica que permite ao desenvolvedor definir e criar uma aplicao bsica qu
pode criar, obter, atualizar e excluir objetos. Scaffold em CakePHP tambm permit
e desenvolvedores definir como objetos so relacionados com outros, e criar e queb
rar essas ligaes.
Tudo que necessrio para criar um scaffold um model e seu controller. Uma vez que
voc configurou a varivel $scaffold no seu controller voc j tem tudo funcionando.
O scaffold do CakePHP muito legal. Ele te d uma aplicao CRUD (Create - Criar, Retri
ve - Obter, Update - Atualizar, Delete - Excluir) totalmente funcional em minuto
s. To legal que voc vai querer us-lo em aplicaes em fase de produo. Agora, ns tambm
mos que ele legal, mas, por favor, perceba que scaffold bem. apenas scaffold. uma
estrutura simples que voc pe para funcionar muito rpido no incio do projeto para ter
algo funcionando o mais rpido possvel. Ele no tem inteno de ser completamente flexvel
, ele mais como uma forma de j comear com algo funcionando. Se voc se perceber prec
isando personalizar suas lgica e suas views, hora deixar de lado seu scaffold e e
screver um pouco de cdigo. O console Bake do CakePHP, coberto em uma sesso mais a
frente, timo prximo passo: ele gera todo o cdigo que produzir um resultado parecido
com o scaffold atual.
Scaffold uma tima forma de lidar com as partes iniciais do desenvolvimento de uma
aplicao web. Esquemas de banco de dados iniciais esto sujeitos a mudanas, o que per
feitamente normal na parte inicial do processo de design. E a existe um problema:
desenvolvedores web detestam criar formulrios que nunca sero realmente usados. Pa
ra reduzir o trabalho do desenvolvedor, o scaffold foi adicionado no CakePHP. Ao
fazer scaffold o CakePHP analiza suas tabelas do banco de dados e cria listas p

adronizadas com botes add, delete e edit, formulrios padres de edio e views padroniza
das para inspeo de itens no banco de dados.
Para adicionar scaffold na sua aplicao, em seu controller adicione a varivel $scaff
old:
<?php
class CategoriasController extends AppController {
var $scaffold;
}
?>
Assumindo que voc criou at mesmo o arquivo de classe model Categoria (em /app/mode
ls/categoria.php), voc est pronto para ir. Visite http://exemplo.com/categorias pa
ra ver seu novo scaffold.
Nota: criar mtodos em controllers que tem scaffold pode causar resultados no desej
ados. Por exemplo, se voc criar uma mtodo index() em um controller com scaffold, s
eu mtodo index ser renderizado ao invs da funcionalidade do scaffold.
O scaffold est ciente das associaes entre models, ento se o seu model Categoria est a
ssociado atravs de belongsTo a um model Usuario, voc ver a listagem de IDs do Usuar
io. Se voc ao invs do ID quer ver outra coisa (como o nome do usurio), voc pode conf
igurar a varivel $displayField no model.
Vamos configurar a varivel $displayField na class Usuario para que as categorias
mostrem usurios pelo nome ao invs de apenas o ID no scaffold. Esse recurso faz com
que o scaffold se torne mais legvel em muitas situaes.
<?php
class Usuario extends AppModel {
var $name = Usuario ;
var $displayField = nome ;
}

?>
Personalizando os scaffolds

Se voc est procurando por algo um pouco diferente em suas views de scaffold, voc po
de criar templates. Ns no recomendamos essa tcnica para aplicaes em nvel de produo, m
esse nvel de personalizao pode ser til durante as fases de interao.
A personalizao feita atravs da criao de templates para as views:
Views scaffold personalizadas para um controller
especfico (PostsController neste exemplo) deve ser colocado assim:
/app/views/posts/scaffold.index.ctp
/app/views/posts/scaffold.show.ctp
/app/views/posts/scaffold.edit.ctp
/app/views/posts/scaffold.new.ctp
Views scaffold para todos os controllers devem ser colocadas assim:
/app/views/scaffolds/index.ctp
/app/views/scaffolds/show.ctp

/app/views/scaffolds/edit.ctp
/app/views/scaffolds/new.ctp
/app/views/scaffolds/add.ctp
3.11 Scaffolding
* Edit
* Comments (2)
* History
Application scaffolding is a technique that allows a developer to define and cre
ate a basic application that can create, retrieve, update and delete objects. Sc
affolding in CakePHP also allows developers to define how objects are related to
each other, and to create and break those links.
All thats needed to create a scaffold is a model and its controller. Once you set
the $scaffold variable in the controller, youre up and running.
CakePHPs scaffolding is pretty cool. It allows you to get a basic CRUD applicatio
n up and going in minutes. So cool that you ll want to use it in production apps
. Now, we think its cool too, but please realize that scaffolding is... well...
just scaffolding. It s a loose structure you throw up real quick during the begi
nning of a project in order to get started. It isn t meant to be completely flex
ible, its meant as a temporary way to get up and going. If you find yourself real
ly wanting to customize your logic and your views, its time to pull your scaffol
ding down in order to write some code. CakePHPs Bake console, covered in the next
section, is a great next step: it generates all the code that would produce the
same result as the most current scaffold.

Scaffolding is a great way of getting the early parts of developing a web applic
ation started. Early database schemas are subject to change, which is perfectly
normal in the early part of the design process. This has a downside: a web devel
oper hates creating forms that never will see real use. To reduce the strain on
the developer, scaffolding has been included in CakePHP. Scaffolding analyzes yo
ur database tables and creates standard lists with add, delete and edit buttons,
standard forms for editing and standard views for inspecting a single item in t
he database.
To add scaffolding to your application, in the controller, add the $scaffold var
iable:
<?php
class CategoriesController extends AppController {
var $scaffold;
}
?>
1.
2.
3.
4.
5.

<?php
class CategoriesController extends AppController {
var $scaffold;
}
?>

Assuming youve created even the most basic Category model class file (in /app/mod
els/category.php), youre ready to go. Visit http://example.com/categories to see
your new scaffold.

Creating methods in controllers that are scaffolded can cause unwanted results.
For example, if you create an index() method in a scaffolded controller, your in
dex method will be rendered rather than the scaffolding functionality.
Scaffolding is knowledgeable about model associations, so if your Category model
belongsTo a User, youll see related User IDs in the Category listings. If youd ra
ther see something besides an ID (like the users first name), you can set the $di
splayField variable in the model.
Lets set the $displayField variable in our User class so that users related to ca
tegories will be shown by first name rather than just an ID in scaffolding. This
feature makes scaffolding more readable in many instances.
<?php
class User extends AppModel {
var $name = User ;
var $displayField = first_name ;
}

?>
<?php
class User extends AppModel {
var $name = User ;
var $displayField = first_name ;
}
?>

1.
2.
3.
4.
5.
6.

3.12 The CakePHP Console


* Edit
* Comments (4)
* History
This section provides an introduction into CakePHP at the command-line. If youve
ever needed access to your CakePHP MVC classes in a cron job or other command-li
ne script, this section is for you.
PHP provides a powerful CLI client that makes interfacing with your file system
and applications much smoother. The CakePHP console provides a framework for cre
ating shell scripts. The Console uses a dispatcher-type setup to load a shell or
task, and hand it its parameters.
A command-line (CLI) build of PHP must be available on the system if you plan to
use the Console.
Before we get into specifics, lets make sure we can run the CakePHP Console. Firs
t, youll need to bring up a system shell. The examples shown in this section will
be in bash, but the CakePHP Console is Windows-compatible as well. Lets execute
the Console program from bash. This example assumes that the user is currently l
ogged into a bash prompt and is currently at the root of a CakePHP installation.
You can technically run the console using something like this:
$ cd /my/cake/app_folder
$ ../cake/console/cake
But the preferred usage is adding the console directory to your path so you can

use the cake command anywhere:


$ cake
Running the Console with no arguments produces this help message:
Hello user,
Welcome to CakePHP v1.2 Console
--------------------------------------------------------------Current Paths:
-working: /path/to/cake/
-root: /path/to/cake/
-app: /path/to/cake/app/
-core: /path/to/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:
app/vendors/shells/:
- none
vendors/shells/:
- none
cake/console/libs/:
acl
api
bake
console
extract

To run a command, type cake shell_name [args]


To get help on a specific command, type cake shell_name help

The first information printed relates to paths. This is especially helpful if yo


ure running the Console from different parts of the filesystem.
Many users add the CakePHP Console to their systems path so it can be accessed ea
sily. Printing out the working, root, app, and core paths allows you to see wher
e the Console will be making changes. To change the app folder you wish to work
with, you can supply its path as the first argument to the cake command. This ne
xt example shows how to specify an app folder, assuming youve already added the c
onsole folder to your PATH:
$ cake -app /path/to/app
The path supplied can be relative to the current working directory or supplied a
s an absolute path.
Traduzindo o core de sua aplicao CakePHP
postado por Gabriel Gilini em 25/09/2008 15:25:48
Tags: cakephp, i18n
Muitos problemas que o desenvolvedor enfrenta durante o projeto so facilmente sol

ucionados se a mensagem de erro for interpretada corretamente. Quem freqenta list


as de discusso sabe como muitas vezes a soluo compreender o problema.
Pensando em quem no fala ingls e utiliza o CakePHP em seus projetos, fiz a traduo de
todas as mensagens internacionalizadas do framework, passando mensagens como as
do console, pgina inicial padro, erros, entre outras, para o portugus.

A instalao das tradues muito simples. Faa o download do arquivo que contm as mensagen
em portugus neste link, e descompacte-o no diretrio app/locale.
$ tar -xzvf pt_br.tar.gz -C <CAMINHO AT SUA APLICAO>/app/locale
Aps a extrao, edite o arquivo core.php localizado no diretrio config da sua aplicao, e
insira a seguinte linha:
<?php
Configure::write( Config.language , pt-br );
?>

E pronto, agora seu Cake fala portugus!


Convido a todos que utilizarem esta traduo a enviarem crticas e sugestes nos comentri
os. Obrigado!

Вам также может понравиться