Manual
Kliknij tutaj aby przejść do wersji 1.1.x manual CakePHP
Witamy w Cookbook, dokumentacji CakePHP. Cookbook jest wiki podobnym systemem, pozwalającym na udział ludzi w rozwoju. Przez ten otwarty system mamy nadzieję utrzymać na wysokim poziomie jakość, wiarygodność, i trafność dokumentacji CakePHP. Cookbook także stwarza możliwość pomocy każdemu.
Ogromne podziękowania dla AD7six który wspomagał rozwój Cookbook przez wyczerpujące godziny, testował i ulepszał tą aplikację.
# How it Works:
- You visit the site and notice an error, something that is incomplete, something that hasn't been covered at all, or something that just isn't worded to your liking.
- Log in to Cookbook using your Bakery account.
- Submit additions/edits for review using valid, semantic HTML.
- Check back in the next day or so to see your changes approved.
- Please review the guidelines for submitting to the Cookbook to ensure consistency.
# Translations
Email John David Anderson (docs at cakephp dot org) or on IRC (#cakephp on freenode as _psychic_) to discuss any translation efforts you would like to participate in.
Translator tips:
- Do not use html entities for accented characters, the book uses UTF-8.
- Use Informal Form.
- Translate both the content and the title at the same time.
- Browse and edit in the language the content is being translated to - otherwise it get's logged as an English Edit with only a slim chance that a reviewer knows what language you are writing in.
- Don't significantly change the markup (HTML) or add new content - If the original content is missing some info, submit an edit for that first.
- Do change any cross-reference links to point at the translated language.
- If you need to write an English term, wrap it in
<em>tags. E.g. "asdf asdf Controller asdf" or "asdf asdf Kontroller (Controller) asfd" as appropriate.
New! get the book's fixed contents in your language by sending the Pot file to either AD7six or Psychic.
We're committed to making the documentation for CakePHP better than it has ever been. We hope you'll join us by using the Cookbook and giving back to a project that we've all benefited so much from.
1 Początki z CakePHP
Patty-cake, patty-cake...
1.1 Czym jest CakePHP? Po co go używać?
CakePHP jest darmowym framework'iem o otwartym kodzie służącym do szybkiego budowania aplikacji dla platformy PHP. Stanowi dla programistów fundamentalną strukturę służącą w budowie aplikacji sieciowych. Naszym głównym celem jest to, aby umożliwić programistą pracę w sposób ustrukturyzowany i szybki, nie tracąc jednocześnie elastyczności.
CakePHP usuwa monotonię podczas tworzenia aplikacji. Zapewniamy wszystkie narzędzia potrzebne do tego, abyś mógł się skupić na rzeczach, które są naprawdę ważne: na logice aplikacji. Zamiast wymyślać koło za każdym razem, gdy rozpoczynasz nowy projekt, pobierz swoją własną kopię CakePHP i zacznij zajmować się tym, co tygryski lubią najbardziej - budowaniem własnej aplikacji.
CakePHP posiada aktywną grupę programistów oraz społeczność, która bardzo wzbogaca cały projekt. Dzięki niemu, nie musisz ponownie tworzyć czegoś, co już dawno zostało wymyślone. Używanie CakePHP oznacza, że rdzeń twojej aplikacji został gruntownie przetestowany oraz że będzie on wciąż udoskonalany.
Oto krótka lista najciekawszych cech CakePHP:
- Aktywna, przyjacielska społeczność
- Elastyczna licencja
- Kompatybilność z wersją 4 i 5 PHP
- Zintegrowany CRUD dla interakcji z bazą danych
- Scaffolding
- Generator kodu
- Architektura trójwarstwowa MVC
- Dyspozytor żądań (Request dispatcher) pozwalający na budowanie prostych adresów URL oraz używanie tras (routes)
- Wbudowany mechanizm walidacji
- Szybkie i elastyczne szablony (składnia PHP wraz z helperami)
- Helpery dla AJAX'a, JavaScript'u, formularzy HTML i innych
- Komponenty Email, Cookie, Security, Session oraz Request Handler
- Elastyczne listy kontroli dostępu - ACL
- Czyszczenie danych
- Elastyczne w użyciu Cach'owanie
- Lokalizacje
- Działa z każdego poziomu serwera, przy braku lub niewielkich zmianach konfiguracji Apache'a
1.2 Gdzie szukać pomocy
The Cookbook
Rozpocząłeś w dobrym miejscu. Ten poradnik powinien być zawsze pierwszym miejscem do którego się udasz, gdy będziesz miał jakieś pytania lub niejasności. Tak jak inne projekty o otwartym kodzie, regularnie zdobywamy nowych użytkowników. Staraj się jak możesz uzyskiwać odpowiedzi na pytania na własną rękę. Będziesz je prawdopodobnie znajdował wolniej, lecz dłużej pozostaną w twej pamięci i odciążysz tym samym osoby zajmujące się wsparciem. Pamiętaj, że zarówno do tego poradnika, jak i do API, masz stały dostęp online.
API
Prosto w sedno sprawy i wprost z samego źródła, API (Application Programming Interface) CakePHP jest najbardziej obszerną i kompleksową dokumentacją, zawierającą wszelkie szczegóły opisujące sposób działania framework'a. Należy pamiętać jednak, że umieszczony jest tam głównie czysty, pozbawiony komentarzy kod.
Kanały IRC
#cakephp @ irc.freenode.net
#cakephp.pl @ irc.freenode.net
Jeżeli mimo usilnych starań, nie znalazłeś odpowiedzi na swoje pytania, spróbuj opisać problem na kanale IRC CakePHP. Zwykle możesz tam zastać część naszych programistów, zwłaszcza wciągu dnia czasu amerykańskiego. Będziemy szczęśliwi mogąc pomóc Ci w rozwiązywaniu Twoich problemów.
The Bakery
CakePHP Bakery jest domem dla wszystkich ciekawych rzeczy jakie dzieją się wokół CakePHP. Odwiedzaj go w poszukiwaniu kursów, instrukcji i przykładowych kawałków kodu. Gdy już odpowiednio zaznajomisz się z CakePHP, zaloguj się do portalu i podziel swą wiedzą z całą społecznością, a zyskasz sławę i fortunę.
CakeForge
CakeForge jest kolejnym miejscem w którym możesz zamieszczać swoje projekty i dzielić je z innymi programistami. Jeżeli szukasz lub chcesz opublikować miażdżący komponent, albo warty fortunę plugin, zapoznaj się z CakeForge.
Oficjalna strona CakePHP
Oficjalna strona CakePHP jest zawsze dobrym miejscem do odwiedzenia. Zawiera odnośniki do najczęściej używanych przez programistów narzędzi, opis nowości, pozwala na pobranie kopii CakePHP oraz na dotację projektu.
Grupy Google
http://groups.google.com/group/cake-php
CakePHP posiada bardzo aktywna Grupę Google. Jest to świetne miejsce, w którym można znaleźć wiele interesujących archiwalnych informacji oraz szybką odpowiedź na najczęściej zadawane pytania.
# The Official CakePHP website
The Official CakePHP website is always a great place to visit. It features links to oft-used developer tools, screencasts, donation opportunities, and downloads.
# The Cookbook
This manual should probably be the first place you go to get answers. As with many other open source projects, we get new folks regularly. Try your best to answer your questions on your own first. Answers may come slower, but will remain longer–and you'll also be lightening our support load. Both the manual and the API have an online component.
# The Bakery
The CakePHP Bakery is a clearing house for all things CakePHP. Check it out for tutorials, case studies, and code examples. Once you’re acquainted with CakePHP, log on and share your knowledge with the community and gain instant fame and fortune.
# The API
Straight to the point and straight from the core developers, the CakePHP API (Application Programming Interface) is the most comprehensive documentation around for all the nitty gritty details of the internal workings of the framework. Its a straight forward code reference, so bring your propeller hat.
# CakeForge
CakeForge is another developer resource you can use to host your CakePHP projects to share with others. If you’re looking for (or want to share) a killer component or a praiseworthy plugin, check out CakeForge.
# The Test Cases
If you ever feel the information provided in the API is not sufficient, check out the code of the test cases provided with CakePHP 1.2. They can serve as practical examples for function and data member usage for a class. In your CakePHP distribution package the test cases are located under
cake/tests/cases
cake/tests/cases
# The IRC channel
#cakephp @ irc.freenode.net
If you’re stumped, give us a holler in the CakePHP IRC channel. Someone from the development team is usually there, especially during the daylight hours for North and South America users. We’d love to hear from you, whether you need some help, want to find users in your area, or would like to donate your brand new sports car.
# The Google Group
http://groups.google.com/group/cake-php
CakePHP also has a very active Google Group. It can be a great resource for finding archived answers, frequently asked questions, and getting answers to immediate problems.
1.3 Objaśnienie architektury Model-View-Controller
Dobrze napisane aplikacje CakePHP są tworzone według wzorca projektowego MVC (Model-Widok-Kontroler, ang. Model-View-Controller). Programowanie z zastosowaniem wzorca MVC rozbija aplikację na trzy zasadnicze części. Model reprezentuje dane aplikacji, widok generuje prezentację danych modelu, a kontroler obsługuje i przekazuje żądania użytkowników.
OBRAZEK
Rysunek 1: Przykładowy przebieg wykonywania żądania MVC
Rysunek 1 pokazuje przykład realizacji żądania MVC w CakePHP. Dla zilustrowania, załóżmy że użytkownik o nazwie Ricardo właśnie kliknął na odnośnik "Kup Ciacho!" na głównej stronie twojej aplikacji.
- Ricardo klika odnośnik wskazujący na http://www.przyklad.pl/cakes/buy i jego przeglądarka wysyła żądanie do serwera www.
- Dyspozytor (ang. dispatcher) analizuje URL żądania (/cakes/buy) i przekazuje je do odpowiedniego kontrolera.
- Kontroler odpowiada za logikę aplikacji. Dla przykładu, może sprawdzić czy użytkownik jest zalogowany.
- Kontroler używa również modeli, aby uzyskać dostęp do danych aplikacji. Z reguły modele reprezentują tabele w bazie danych, ale mogą równie dobrze reprezentować wpisy LDAP lub pliki na dysku. W tym przykładzie, kontroler używa modelu w celu wyciągnięcia informacji o ostatnich zakupach użytkownika Ricardo z bazy danych.
- Gdy kontroler przetworzy wyciągnięte dane, przekazuje je do widoku. Widok przygotowuje te dane do wyświetlenia użytkownikowi. Widoki w CakePHP mają najczęściej format HTML, ale mogą one z równym powodzeniem być w formacie PDF, dokumentu XML lub obiektu JSON, w zależności od twoich potrzeb.
- Po tym jak widok użył danych z kontrolera do wygenerowania zawartości, zawartość ta jest wysyłana do przeglądarki Ricardo.
Prawie każde żądanie wysyłane do twojej aplikacji będzie przebiegać w podobny sposób. W dalszej części podręcznika uzupełnimy ten proces o szczegóły specyficzne dla Cake, więc miej go na uwadze, gdy będziemy iść dalej.
1.3.1 Korzyści
Czemu warto stosować MVC? Ponieważ jest to sprawdzony i pewny wzorzec projektowy, który czyni aplikację łatwym w utrzymaniu, modularnym, szybko rozbudowywalnym pakietem. Rozbijanie zadań aplikacji na oddzielne modele, widoki i kontrolery powoduje, że aplikacja ma przejrzystą strukturę. Łatwo dodać nową funkcjonalność, a dodanie nowego wyglądu dla starej funkcjonalności to pestka. Modularna architektura z separacją widoku od logiki aplikacji pozwala developerom i grafikom pracować równolegle, włączając w to możliwość szybkiego prototypowania. Separacja umożliwia także developerom dokonywania zmian w jednej części aplikacji, nie naruszając pozostałych.
Jeśli nie budowałeś jeszcze aplikacji w taki sposób, przyzwyczajenie się do tej metody wymaga nieco czasu. Jesteśmy jednak pewni, że gdy już zbudujesz swoją pierwszą aplikację w CakePHP, nie będziesz chciał stosować żadnej innej.
2 Podstawowe zasady CakePHP.
Framework CakePHP dostarcza silną podstawę dla Twojej aplikacji. Radzi sobie w każdym aspekcie, od podstawowych elementów po końcowe wykonanie strony. Framework CakePHP wprowadzi Cie w zasady działania MVC, pozwoli Ci na na łatwe dostosowanie i rozszerzenie pod każdym względem Twojej aplikacji
Framework także wprowadza organizację struktury, od nazw plików po nazwy tabel bazy danych, utrzymuje Twoją aplikację logiczną i uporządkowaną. Ta koncepcja jest prosta ale bardzo potężna. Podąża za konwencjami i zawsze wiesz dokładnie gdzie są dane elementy i jak są zorganizowane.
2.1 CakePHP Structure
CakePHP features Controller, Model, and View classes, but it also features some additional classes and objects that make development in MVC a little quicker and more enjoyable. Components, Behaviors, and Helpers are classes that provide extensibility and reusability to quickly add functionality to the base MVC classes in your applications. Right now we’ll stay at a higher level, so look for the details on how to use these tools later on.
2.1.1 Controller Extensions ("Components")
A Component is a class that aids in controller logic. If you have some logic you want to share between controllers (or applications), a component is usually a good fit. As an example, the core EmailComponent class makes creating and sending emails a snap. Rather than writing a controller method in a single controller that performs this logic, you can package the logic so it can be shared.
Controllers are also fitted with callbacks. These callbacks are available for your use, just in case you need to insert some logic between CakePHP’s core operations. Callbacks available include:
beforeFilter(), executed before any controller action logicbeforeRender(), executed after controller logic, but before the view is renderedafterFilter(), executed after all controller logic, including the view render. There may be no difference betweenafterRender()andafterFilter()unless you’ve manually made a call torender()in your controller action and have included some logic after that call.
2.1.2 View Extensions ("Helpers")
A Helper is a class that aids in view logic. Much like a component used among controllers, helpers allow presentational logic to be accessed and shared between views. One of the core helpers, AjaxHelper, makes Ajax requests within views much easier.
Most applications have pieces of view code that are used repeatedly. CakePHP facilitates view code reuse with layouts and elements. By default, every view rendered by a controller is placed inside a layout. Elements are used when small snippets of content need to be reused in multiple views.
2.1.3 Model Extensions ("Behaviors")
Similarly, Behaviors work as ways to add common functionality between models. For example, if you store user data in a tree structure, you can specify your User model as behaving like a tree, and gain free functionality for removing, adding, and shifting nodes in your underlying tree structure.
Models also are supported by another class called a DataSource. DataSources are an abstraction that enable models to manipulate different types of data consistently. While the main source of data in a CakePHP application is often a database, you might write additional DataSources that allow your models to represent RSS feeds, CSV files, LDAP entries, or iCal events. DataSources allow you to associate records from different sources: rather than being limited to SQL joins, DataSources allow you to tell your LDAP model that it is associated to many iCal events.
Just like controllers, models are featured with callbacks as well:
- beforeFind()
- afterFind()
- beforeValidate()
- beforeSave()
- afterSave()
- beforeDelete()
- afterDelete()
The names of these methods should be descriptive enough to let you know what they do. You can find the details in the models chapter.
2.1.4 Application Extensions
Controllers, helpers and models each have a parent class you can use to define application-wide changes. AppController (located at /app/app_controller.php), AppHelper (located at /app/app_helper.php) and AppModel (located at /app/app_model.php) are great places to put methods you want to share between all controllers, helpers or models.
Although they aren’t classes or files, routes play a role in requests made to CakePHP. Route definitions tell CakePHP how to map URLs to controller actions. The default behavior assumes that the URL “/controller/action/var1/var2” maps to Controller::action($var1, $var2), but you can use routes to customize URLs and how they are interpreted by your application.
Some features in an application merit packaging as a whole. A plugin is a package of models, controllers and views that accomplishes a specific purpose that can span multiple applications. A user management system or a simplified blog might be a good fit for CakePHP plugins.
2.2 A Typical CakePHP Request
We’ve covered the basic ingredients in CakePHP, so let’s look at how objects work together to complete a basic request. Continuing with our original request example, let’s imagine that our friend Ricardo just clicked on the “Buy A Custom Cake Now!” link on a CakePHP application’s landing page.

Figure: 2. Typical Cake Request.
Black = required element, Gray = optional element, Blue = callback
- Ricardo clicks the link pointing to http://www.example.com/cakes/buy, and his browser makes a request to your web server.
- The Router parses the URL in order to extract the parameters for this request: the controller, action, and any other arguments that will affect the business logic during this request.
- Using routes, a request URL is mapped to a controller action (a method in a specific controller class). In this case, it’s the buy() method of the CakesController. The controller’s beforeFilter() callback is called before any controller action logic is executed.
- The controller may use models to gain access to the application’s data. In this example, the controller uses a model to fetch Ricardo’s last purchases from the database. Any applicable model callbacks, behaviors, and DataSources may apply during this operation. While model usage is not required, all CakePHP controllers initially require at least one model.
- After the model has retrieved the data, it is returned to the controller. Model callbacks may apply.
- The controller may use components to further refine the data or perform other operations (session manipulation, authentication, or sending emails, for example).
- Once the controller has used models and components to prepare the data sufficiently, that data is handed to the view using the controller’s set() method. Controller callbacks may be applied before the data is sent. The view logic is performed, which may include the use of elements and/or helpers. By default, the view is rendered inside of a layout.
- Additional controller callbacks (like afterFilter) may be applied. The complete, rendered view code is sent to Ricardo’s browser.
2.3 CakePHP File Structure
Let’s take a look at what CakePHP looks like right out of the box. You know what CakePHP looks like from a basic MVC request standpoint, but you’ll need to know how its files are organized as well.
- app
- cake
- docs
- index.php
- vendors
When you download CakePHP, you will see four main folders. The app folder will be where you work your magic: it’s where your application’s files will be placed. The cake folder is where we’ve worked our magic. Make a personal commitment not to edit files in this folder. We can’t help you if you’ve modified the core. The docs folder is for the quintessential readme, changelog, and licensing information. Finally, the vendors folder is where you’ll place third-party PHP libraries you need to use with your CakePHP applications.
2.3.1 The App Folder
CakePHP’s app folder is where you will do most of your application development. Let’s look a little closer at the folders inside of app.
| config | Holds the (few) configuration files CakePHP uses. Database connection details, bootstrapping, core configuration files and more should be stored here. |
|---|---|
| controllers | Contains your application’s controllers and their components. |
| locale | Stores string files for internationalization. |
| models | Contains your application’s models, behaviors, and datasources. |
| plugins | Contains plugin packages. |
| tmp | This is where CakePHP stores temporary data. The actual data it stores depends on how you have CakePHP configured, but this folder is usually used to store model descriptions, logs, and sometimes session information. |
| vendors | Any third-party classes or libraries should be placed here. Doing so makes them easy to access using the App::import('vendor', 'name') function. Keen observers will note that this seems redundant, as there is also a vendors folder at the top level of our directory structure. We'll get into the differences between the two when we discuss managing multiple applications and more complex system setups. |
| views | Presentational files are placed here: elements, error pages, helpers, layouts, and view files. |
| webroot | In a production setup, this folder should serve as the document root for your application. Folders here also serve as holding places for CSS stylesheets, images, and JavaScript files. |
2.4 CakePHP Conventions
We’re a big fan of convention over configuration. While it takes a bit of time to learn CakePHP’s conventions, you save time in the long run: by following convention, you get free functionality, and you free yourself from the maintenance nightmare of tracking config files. Convention also makes for a very uniform system development, allowing other developers to jump in and help more easily.
CakePHP’s conventions have been distilled out of years of web development experience and best practices. While we suggest you use these conventions while developing with CakePHP, we should mention that many of these tenets are easily overridden–something that is especially handy when working with legacy systems.
2.4.1 File and Classname Conventions
In general, filenames are underscored while classnames are CamelCased. So if you have a class MyNiftyClass, then in Cake, the file should be named my_nifty_class.php. Below are examples of how to name the file for each of the different types of classes you would typically use in a CakePHP application:
- The Controller class KissesAndHugsController would be found in a file named kisses_and_hugs_controller.php (notice _controller in the filename)
- The Component class MyHandyComponent would be found in a file named my_handy.php
- The Model class OptionValue would be found in a file named option_value.php
- The Behavior class EspeciallyFunkableBehavior would be found in a file named especially_funkable.php
- The View class SuperSimpleView would be found in a file named super_simple.ctp
- The Helper class BestEverHelper would be found in a file named best_ever.php
Each file would be located in or under (can be in a subfolder) the appropriate folder in your app folder.
2.4.2 Model and Database Conventions
Model classnames are singular and CamelCased. Person, BigPerson, and ReallyBigPerson are all examples of conventional model names.
Table names corresponding to CakePHP models are plural and underscored. The underlying tables for the above mentioned models would be people, big_people, and really_big_people, respectively.
Foreign keys in hasMany, belongsTo or hasOne relationships are recognized by default as the (singular) name of the related model followed by _id. So if a baker hasMany cakes, the cakes table will refer to the baker in the bakers table via a baker_id foreign key.
Join tables, used in hasAndBelongsToMany (HABTM) relationships between models should be named after the model tables they will join in alphabetical order (apples_zebras rather than zebras_apples).
All tables with which CakePHP models interact (with the exception of join tables), require a singular primary key to uniquely identify each row. If you wish to model a table which does not have a single-field primary key, such as the rows of your posts_tags join table, CakePHP's convention is that a single-field primary key is added to the table.
CakePHP does not support composite primary keys. If you want to directly manipulate your join table data, use direct query calls or add a primary key to act on it as a normal model. E.g.:
CREATE TABLE posts_tags ( id INT(10) NOT NULL AUTO_INCREMENT, post_id INT(10) NOT NULL, tag_id INT(10) NOT NULL, PRIMARY KEY(id));
2.4.3 Controller Conventions
Controller classnames are plural, CamelCased, and end in Controller. PeopleController and LatestArticlesController are both examples of conventional controller names.
The first function you write for a controller might be the index() function. When a request specifies a controller but not an action, the default CakePHP behavior is to execute the index() function of that controller. For example, a request for http://www.example.com/apples/ maps to a call on the index() function of the ApplesController, whereas http://www.example.com/apples/view/ maps to a call on the view() function of the ApplesController.
You can also change the visibility of controller functions in CakePHP by prefixing controller function names with underscores. If a controller function has been prefixed with an underscore, the function will not be accessible directly from the web but is available for internal use. For example:
<?php
class NewsController extends AppController {
function latest() {
$this->_findNewArticles();
}
function _findNewArticles() {
//Logic to find latest news articles
}
}
?>
<?phpclass NewsController extends AppController {function latest() {$this->_findNewArticles();}function _findNewArticles() {//Logic to find latest news articles}}?>
While the page http://www.example.com/news/latest/ would be accessible to the user as usual, someone trying to get to the page http://www.example.com/news/_findNewArticles/ would get an error, because the function is preceded with an underscore.
2.4.3.1 URL Considerations for Controller Names
As you've just seen, single word controllers map easily to a simple lower case URL path. For example, ApplesController (which would be defined in the file name 'apples_controller.php') is accessed from http://example.com/apples.
Multiple word controllers can be any 'inflected' form which equals the controller name so:
- /redApples
- /RedApples
- /Red_apples
- /red_apples
will all resolve to the index of the RedApples controller. However, the convention is that your urls are lowercase and underscored, therefore /red_apples/go_pick is the correct form to access the RedApplesController::go_pick action.
2.4.4 View Conventions
View template files are named after the controller functions they display, in an underscored form. The getReady() function of the PeopleController class will look for a view template in /app/views/people/get_ready.ctp.
The basic pattern is /app/views/controller/underscored_function_name.ctp.
By naming the pieces of your application using CakePHP conventions, you gain functionality without the hassle and maintenance tethers of configuration. Here’s a final example that ties the conventions
- Database table: "people"
- Model class: "Person", found at /app/models/person.php
- Controller class: "PeopleController", found at /app/controllers/people_controller.php
- View template, found at /app/views/people/index.ctp
Using these conventions, CakePHP knows that a request to http://example.com/people/ maps to a call on the index() function of the PeopleController, where the Person model is automatically available (and automatically tied to the ‘people’ table in the database), and renders to a file. None of these relationships have been configured by any means other than by creating classes and files that you’d need to create anyway.
Now that you've been introduced to CakePHP's fundamentals, you might try a run through the CakePHP Blog Tutorial to see how things fit together.
3 Developing with CakePHP
Now you’re cooking.
3.1 Wymagania
- Serwer HTTP. Preferowany jest Apache z modułem mod_rewrite ale możesz użyć innego.
- PHP w wersji 4.3.2 lub wyższej. Tak, CakePHP działa świetnie na PHP4 i PHP5.
Technicznie rzecz biorąc baza dancyh nie jest wymagana, ale zwykle każda aplikacja internetowa jakiejś używa. CakePHP wspiera różne silniki bazodanowe:
- MySQL (wersja 4 lub późniejsza)
- PostgreSQL
- Firebird DB2
- Microsoft SQL Server
- Oracle
- SQLite
- ODBC
- ADOdb
3.2 Przygotowanie do instalacji.
Instalacja CakePHP jest bardzo łatwa i szybka. Minimalne wymagania to serwer www i kopia CakePHP. Ten manual skupia się na instalacji z Apache (ponieważ jest on najbardziej powszechny), możesz skonfigurować CakePHP na różnych serwerach www takich jak LightHTTPD lub Microsoft IIS
Przygotowanie instalacji polega na poszczególnych krokach
- Pobraniu kopii CakePHP
- Konfiguracji Twojego serwera do obsługi PHP (jeśli zajdzie taka potrzeba)
- Sprawdzeniu praw dostępu do plików
3.2.1 Pobranie CakePHP
Są dwie możliwości pobrania aktualnej wersji CakePHP. Pierwsza to ściągnięcie archiwum (zip/tar.gz/tar.bz2), druga to pobranie źródeł z repozytorium SVN.
Aby pobrać aktualną wersję wejdź na stronę http://www.cakephp.org. Kliknij ogromny link do raju “Download Now!”. Pliki Cake-a są zamieszczona na CakeForge więc możesz także wejść na stronę projektu http://cakeforge.org/projects/cakephp.
Jeśli chcesz żyć na krawędzi sprawdź nasze "nocne" (nightly) wersje. Wersje "nocne" CakePHP są stabilne i zawierają poprawki dodawane pomiędzy oficjalnymi wydaniami.
Aby obrać aktualną kopię źródeł z naszego repozytorium SVN połącz się z https://svn.cakephp.org/repo/branches/1.2.x.x .
3.2.2 Prawa dostępu.
CakePHP używa katalogu /app/tmp dla różnych operacji. Opis modelu, cache widoku, informacje o sesji to tylko kilka przykładów
Upewnij się, że katalog /app/tmp w twojej instalacji CakePHP ma prawa do zapisu przez użytkownika
3.3 Installation
Installing CakePHP can be as simple as slapping it in your web server’s document root, or as complex and flexible as you wish. This section will cover the three main installation types for CakePHP: development, production, and advanced.
- Development: easy to get going, URLs for the application include the CakePHP installation directory name, and less secure.
- Production: Requires the ability to configure the web server’s document root, clean URLs, very secure.
- Advanced: With some configuration, allows you to place key CakePHP directories in different parts of the filesystem, possibly sharing a single CakePHP core library folder amongst many CakePHP applications.
3.3.1 Development
A development installation is the fastest method to setup Cake. This example will help you install a CakePHP application and make it available at http://www.example.com/cake_1_2/. We assume for the purposes of this example that your document root is set to /var/www/html.
Unpack the contents of the Cake archive into /var/www/html. You now have a folder in your document root named after the release you've downloaded (e.g. cake_1.2.0.7296-rc2). Rename this folder to cake_1_2. Your development setup will look like this on the file system:
- /var/www/html
- /cake_1_2
- /app
- /cake
- /docs
- /vendors
- /index.php
- /cake_1_2
If your web server is configured correctly, you should now find your Cake application accessible at http://www.example.com/cake_1_2/.
3.3.2 Production
A production installation is a more flexible way to setup Cake. Using this method allows an entire domain to act as a single CakePHP application. This example will help you install Cake anywhere on your filesystem and make it available at http://www.example.com. Note that this installation may require the rights to change the DocumentRoot on an Apache webservers.
Unpack the contents of the Cake archive into a directory of your choosing. For the purposes of this example, we assume you choose to install Cake into /cake_install. Your production setup will look like this on the filesystem:
- /cake_install/
- /app
- /webroot (this directory is set as the
DocumentRootdirective)
- /webroot (this directory is set as the
- /cake
- /docs
- /vendors
- /index.php
- /app
Developers using Apache should set the DocumentRoot directive for the domain to:
DocumentRoot /cake_install/app/webroot
If your web server is configured correctly, you should now find your Cake application accessible at http://www.example.com.
3.3.3 Advanced Installation
There may be some situations where you wish to place CakePHP's directories on different places on the filesystem. This may be due to a shared host restriction, or maybe you just want a few of your apps to share the same Cake libraries. This section describes how to spread your CakePHP directories across a filesystem.
First, realize that there are three main parts to a Cake application:
- The core CakePHP libraries, in /cake.
- Your application code, in /app.
- The application’s webroot, usually in /app/webroot.
Each of these directories can be located anywhere on your file system, with the exception of the webroot, which needs to be accessible by your web server. You can even move the webroot folder out of the app folder as long as you tell Cake where you've put it.
To configure your Cake installation, you'll need to make some changes to /app/webroot/index.php. There are three constants that you'll need to edit: ROOT, APP_DIR, and CAKE_CORE_INCLUDE_PATH.
ROOTshould be set to the path of the directory that contains your app folder.APP_DIRshould be set to the path of your app folder.CAKE_CORE_INCLUDE_PATHshould be set to the path of your CakePHP libraries folder.
Let’s run through an example so you can see what an advanced installation might look like in practice. Imagine that I wanted to set up CakePHP to work as follows:
- The CakePHP core libraries will be placed in /usr/lib/cake.
- My application’s webroot directory will be /var/www/mysite/.
- My application’s app directory will be stored in /home/me/mysite.
Given this type of setup, I would need to edit my webroot/index.php file (which will end up at /var/www/mysite/index.php, in this example) to look like the following:
// /app/webroot/index.php (partial, comments removed)
if (!defined('ROOT')) {
define('ROOT', DS.'home'.DS.'me');
}
if (!defined('APP_DIR')) {
define ('APP_DIR', 'mysite');
}
if (!defined('CAKE_CORE_INCLUDE_PATH')) {
define('CAKE_CORE_INCLUDE_PATH', DS.'usr'.DS.'lib'.DS.'cake');
}
// /app/webroot/index.php (partial, comments removed)if (!defined('ROOT')) {define('ROOT', DS.'home'.DS.'me');}if (!defined('APP_DIR')) {define ('APP_DIR', 'mysite');}if (!defined('CAKE_CORE_INCLUDE_PATH')) {define('CAKE_CORE_INCLUDE_PATH', DS.'usr'.DS.'lib'.DS.'cake');}
It is recommended to use the DS constant rather than slashes to delimit file paths. This prevents any missing file errors you might get as a result of using the wrong delimiter, and it makes your code more portable.
3.3.3.1 Additional Class Paths
It’s occasionally useful to be able to share MVC classes between applications on the same system. If you want the same controller in both applications, you can use CakePHP’s bootstrap.php to bring these additional classes into view.
In bootstrap.php, define some specially-named variables to make CakePHP aware of other places to look for MVC classes:
$viewPaths = array(); $controllerPaths = array(); $modelPaths = array(); $helperPaths = array(); $componentPaths = array(); $behaviorPaths = array();
$viewPaths = array();$controllerPaths = array();$modelPaths = array();$helperPaths = array();$componentPaths = array();$behaviorPaths = array();
Each of these special variables can be set to an array of absolute filesystem paths where extra classes can be found when requested. Make sure that each path specified includes a trailing slash.
3.3.4 Apache and mod_rewrite
While CakePHP is built to work with mod_rewrite out of the box–and usually does–we've noticed that a few users struggle with getting everything to play nicely on their systems. Here are a few things you might try to get it running correctly:
- Make sure that an .htaccess override is allowed. In your httpd.conf, you should have a section that defines your Directory on the server. Make sure the AllowOverride is set to All for the correct DocumentRoot.
- Make sure you are editing the system httpd.conf rather than a user- or site-specific httpd.conf.
- Is CakePHP missing its needed .htaccess files? This sometimes happens during copying or moving because some operating systems treat files that start with '.' as hidden. Make sure your copy of CakePHP is from the downloads section of the site or our SVN repository, and has been unpacked correctly.
- Make sure you are loading up mod_rewrite correctly. You should see something like LoadModule rewrite_module libexec/httpd/mod_rewrite.so (Unix/Linux users should also see something like AddModule mod_rewrite.c) in your httpd.conf. Also make sure that those lines have not been commented out (by being prepended with a #). Restart Apache to make sure your conf settings are active.
- If you are installing CakePHP into a user directory (http://example.com/~username/cakephp/), or any other URL structure that already utilizes mod_rewrite, you'll need to add RewriteBase statements to the .htaccess files CakePHP uses (/.htaccess, /app/.htaccess, /app/webroot/.htaccess). The details of those changes will depend on your setup. Please refer to Apache's online documentation for more information.
3.3.5 Fire It Up
Alright, let's see CakePHP in action. Depending on which setup you used, you should point your browser to http://example.com/ or http://example.com/cake_install/. At this point, you'll be presented with CakePHP's default home, and a message that tells you the status of your current database connection.
Congratulations! You are ready to create your first CakePHP application.
3.4 Configuration
Configuring a CakePHP application is a piece of cake. After you have installed CakePHP, creating a basic web application requires only that you setup a database configuration.
There are, however, other optional configuration steps you can take in order to take advantage of CakePHP flexible architecture. You can easily add elements to the CakePHP core, configure custom URLs, and define custom inflections.
3.4.1 Konfiguracja bazy danych
Cake PHP używa konfiguracji bazy danych zapisanej w pliku app/config/database.php. Przykładowy plik konfiguracyjny można znaleźć w app/config/database.php.default. Końcowa konfiguracja powinna wyglądać mniej więcej tak:
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' => '');
Tablica $default jest używana dopóki inne połączenie nie jest zdefiniowane we właściwości $useDbConfig w modelu. Dla przykładu jeśli nasza aplikacja wykorzystuje dodatkową bazę danych nie użytą w tablicy $default. Możemy użyć jej w naszym modelu przez stworzenie nowego połączenia z bazą danych $legacy na podobnej zasadzie co nasza tablica $default przez ustawienie var $useDbConfig = 'legacy' w wykorzystywanym modelu.
Wypełnij pary klucz/wartość w tablicy konfiguracyjnej w takiej postaci jakiej potrzebujesz
| Klucz | Wartość |
|---|---|
| driver | Nazwa sterownika bazy danych dla którego ta tablica konfiguracyjna jest stworzona. Przykład: mysql, postgres, sqlite, pear-drivername, adodb-drivername, mssql, oracle, lub odbc. | persistent | Używa czy nie, stałego połączenia z bazą dancych |
| host | Host serwera bazy danych (lub adres IP). |
| login | Nazwa użytkownika dla konta |
| password | Hasło użytkownika do konta |
| database | Nazwa bazy danych |
| prefix (opcjonalnie) | ciąg znaków który poprzedza wszystkie nazwy tabel w bazie danych. Jeśli Twoje tabele nie posiadają prefiksów, Pozostaw tą wartość pustą. |
| port (opcjonalnie) | Port TCP dla Unix do połączenia z serwerem. |
| encoding | Ustawia kodowanie znaków używanych przez bazę danych. |
| schema | Używane w bazie PostgreSQL ustawia jakiego schematu używać. |
Opcja prefix jest dla tabel, NIE modeli. Dla przykładu jeśli Tworzysz tabelę spajającą Twoje modele Apple i Flavour , nazwij je prefix_apples_flavors (NIE prefix_apples_prefix_flavors), i ustaw swój prefix na 'prefix_'.
Możesz także zajrzeć CakePHP-Conventions. Poprawne nazewnictwo Twoich tabel (i dodatkowych tabel) możesz zyskać swobodnej funkcjonalności i pomoże Ci ustrzec się od konfiguracji. Przykładowo jeśli nazwiesz swoją tabelę bazy danych big_boxes, model BigBox, kontroler BigBoxesController, wszystko będzie działać razem automatycznie. Używaj podkreśleń, małych liter, liczb mnogich dla Twoich baz danych. Przykład: bakers, pastry_stores, i savory_cakes.
3.4.2 Core Configuration
Application configuration in CakePHP is found in /app/config/core.php. This file is a collection of Configure class variable definitions and constant definitions that determine how your application behaves. Before we dive into those particular variables, you’ll need to be familiar with Configure, CakePHP’s configuration registry class.
3.4.3 The Configuration Class
Despite few things needing to be configured in CakePHP, it’s sometimes useful to have your own configuration rules for your application. In the past you may have defined custom configuration values by defining variable or constants in some files. Doing so forces you to include that configuration file every time you needed to use those values.
CakePHP’s new Configure class can be used to store and retrieve application or runtime specific values. Be careful, this class allows you to store anything in it, then use it in any other part of your code: a sure temptation to break the MVC pattern CakePHP was designed for. The main goal of Configure class is to keep centralized variables that can be shared between many objects. Remember to try to live by "convention over configuration" and you wont end up breaking the MVC structure we’ve set in place.
This class acts as a singleton and its methods can be called from anywhere within your application, in a static context.
<?php Configure::read('debug'); ?>
<?php Configure::read('debug'); ?>
3.4.3.1 Configure Methods
3.4.3.1.1 write
write(string $key, mixed $value)
Use write() to store data in the application’s configuration.
Configure::write('Company.name','Pizza, Inc.');
Configure::write('Company.slogan','Pizza for your body and soul');
Configure::write('Company.name','Pizza, Inc.');Configure::write('Company.slogan','Pizza for your body and soul');
the usage of dot notation in the $key parameter. You can use this notation to organize your configuration into logical groups.
The above example could also be written in a single call:
Configure::write(
'Company',array('name'=>'Pizza, Inc.','slogan'=>'Pizza for your body and soul')
);
Configure::write('Company',array('name'=>'Pizza, Inc.','slogan'=>'Pizza for your body and soul'));
You can use Configure::write('debug', $int) to switch between debug and production modes on the fly. This is especially handy for AMF or SOAP interactions where debugging information can cause parsing problems.
3.4.3.1.2 read
read(string $key = 'debug')
Used to read configuration data from the application. Defaults to CakePHP’s important debug value. If a key is supplied, the data is returned. Using our examples from write() above, we can read that data back:
Configure::read('Company.name'); //yields: 'Pizza, Inc.'
Configure::read('Company.slogan'); //yields: 'Pizza for your body and soul'
Configure::read('Company');
//yields:
array('name' => 'Pizza, Inc.', 'slogan' => 'Pizza for your body and soul');
Configure::read('Company.name'); //yields: 'Pizza, Inc.'Configure::read('Company.slogan'); //yields: 'Pizza for your body and soul'Configure::read('Company');//yields:array('name' => 'Pizza, Inc.', 'slogan' => 'Pizza for your body and soul');
3.4.3.1.3 delete
delete(string $key)
Used to delete information from the application’s configuration.
Configure::delete('Company.name');
Configure::delete('Company.name');
3.4.3.1.4 load
load(string $path)
Use this method to load configuration information from a specific file.
// /app/config/messages.php:
<?php
$config['Company']['name'] = 'Pizza, Inc.';
$config['Company']['slogan'] = 'Pizza for your body and soul';
$config['Company']['phone'] = '555-55-55';
?>
<?php
Configure::load('messages');
Configure::read('Company.name');
?>
// /app/config/messages.php:<?php$config['Company']['name'] = 'Pizza, Inc.';$config['Company']['slogan'] = 'Pizza for your body and soul';$config['Company']['phone'] = '555-55-55';?><?phpConfigure::load('messages');Configure::read('Company.name');?>
Every configure key-value pair is represented in the file with the $config array. Any other variables in the file will be ignored by the load() function.
3.4.3.1.5 version
version()
Returns the CakePHP version for the current application.
3.4.3.2 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 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 'high' and 'medium' also enable session.referer_check |
| 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. |
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.
3.4.3.3 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. |
3.4.4 The App Class
Loading additional classes has become more streamlined in CakePHP. In previous versions there were different functions for loading a needed class based on the type of class you wanted to load. These functions have been deprecated, all class and library loading should be done through App::import() now. App::import() ensures that a class is only loaded once, that the appropriate parent class has been loaded, and resolves paths automatically in most cases.
3.4.4.1 Using App::import()
App::import($type, $name, $parent, $search, $file, $return);
At first glance App::import seems complex, however in most use cases only 2 arguments are required.
3.4.4.2 Importing Core Libs
Core libraries such as Sanitize, and Xml can be loaded by:
App::import('Core', 'Sanitize'); App::import('Core', 'Sanitize');
The above would make the Sanitize class available for use.
3.4.4.3 Importing Controllers, Models, Components, Behaviors, and Helpers
All application related class should also be loaded with App::import(). The following examples illustrate how to do so.
3.4.4.3.1 Loading Controllers
App::import('Controller', 'MyController');
3.4.4.3.2 Loading Models
App::import('Model', 'MyModel');
3.4.4.3.3 Loading Components
App::import('Component', 'Auth');
3.4.4.3.4 Loading Behaviors
App::import('Behavior', 'Tree');
3.4.4.3.5 Loading Helpers
App::import('Helper', 'Html');
3.4.4.4 Loading from Plugins
Loading classes in plugins works much the same as loading app and core classes except you must specify the plugin you are loading from.
App::import('Model', 'PluginName.Comment'); App::import('Model', 'PluginName.Comment');
3.4.4.5 Loading Vendor Files
The vendor() function has been deprecated. Vendor files should now be loaded through App::import() as well. The syntax and additional arguments are slightly different, as vendor file structures can differ greatly, and not all vendor files contain classes.
The following examples illustrate how to load vendor files from a number of path structures. These vendor files could be located in any of the vendor folders.
3.4.4.5.1 Vendor examples
To load vendors/geshi.php
App::import('Vendor', 'geshi'); App::import('Vendor', 'geshi');
To load vendors/flickr/flickr.php
App::import('Vendor', 'flickr/flickr'); App::import('Vendor', 'flickr/flickr');
To load vendors/some.name.php
App::import('Vendor', 'SomeName', array('file' => 'some.name.php')); App::import('Vendor', 'SomeName', array('file' => 'some.name.php'));
To load vendors/services/well.named.php
App::import('Vendor', 'WellNamed', array('file' => 'services'.DS.'well.named.php')); App::import('Vendor', 'WellNamed', array('file' => 'services'.DS.'well.named.php'));
3.4.5 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.
As will be explained later, routes in CakePHP 1.2 have been expanded and are now very powerful.
3.4.5.1 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
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.
3.4.5.2 Named parameters
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';
3.4.5.3 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 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.
Another common use for the Router is to define an "alias" for a controller. Let's say that instead of accessing our regular URL at /users/someAction/5, we'd like to be able to access it by /cooks/someAction/5. The following route easily takes care of that:
Router::connect(
'/cooks/:action/*', array('controller' => 'users', 'action' => 'index')
);
Router::connect('/cooks/:action/*', array('controller' => 'users', 'action' => 'index'));
This is telling the Router that any url beginning with /cooks/ should be sent to the users controller.
When generating urls, routes are used too. Using array('controller' => 'users', 'action' => 'someAction', 5) as a url will output /users/someAction/5 if the above route is the first match found
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',