1 Creating a simple application using the Akelos Framework
2 =========================================================
5 --------------------------
7 This tutorial teaches you how to create an application using the Akelos Framework.
9 The application will be used for managing books and their authors and will be named **booklink**
11 Requisites for this tutorial
12 ---------------------------
14 - A MySQL or SQLite Database
16 - Shell access to your server
19 This setting can be found on most Linux boxes and hosting providers. Akelos works in a myriad of settings but this tutorial focusses on this specific configuration.
21 Download and installation
22 ---------------------------
23 We highly recommend you to get the trunk version of Akelos until we hit version 1.0. You need to have installed [subversion](http://subversion.tigris.org/).
24 You can checkout a working copy of the Akelos source code with the command:
26 svn co http://svn.akelos.org/trunk/ akelos
28 If you can't or don't want to checkout the code from subversion, you can get the [latest stable version](http://www.akelos.org/akelos_framework-dev_preview.tar.gz) generated automatically by the Continuous Integration system, and untar it by typing:
30 tar zxvf akelos_framework-dev_preview.tar.gz;mv akelos_framework-dev_preview akelos
32 Now we need to be sure that akelos can find your PHP version by running
36 If you see something like
38 PHP 5.1.2 (cli) (built: Jan 17 2006 15:00:28)
39 Copyright (c) 1997-2006 The PHP Group
40 Zend Engine v2.1.0, Copyright (c) 1998-2006 Zend Technologies
42 you're on the right track and can continue creating an Akelos application; otherwise you'll need to find out the path to your PHP binary, usually with
46 And change the `#!/usr/bin/env php` at the beginning of these files `script/console`, `script/generate`, `script/migrate`, `script/setup` and `script/test` to your php binary path.
48 **Note for Windows users:** You will need to call the scripts from your application directory using the full path to your php.exe file like:
50 C:\Program Files\xampp\php\php.exe ./script/generate scaffold
52 Setting up a new Akelos application
53 ---------------------------------------------
55 You have downloaded Akelos and made sure you'll be able to run PHP scripts from your console (not necessary to run Akelos, but it's required for this tutorial)
57 Now you can follow two paths:
59 1. Create an Akelos application in a different folder and link it to the Framework libraries.
60 2. Start coding your application from this folder with the security implications that has making available to the visitors of your site all your Application models, views, 3rd party libraries and so on.
62 As you might have guessed you should go with the first option and create a linked Akelos application which will only expose the public folder to the world. Changing the Framework paths is really simple in Akelos, all you have to do is define in your configuration file where each component is located, but we will leave this for a future tutorial about designing an application for distributing it.
64 Assuming you've downloaded the framework to `HOME_DIR/akelos` and that you are inside the `akelos` directory you will check available options for setting up your new application by running
68 which will show us available options for the installer
70 Usage: setup [-sqphf --dependencies] <-d>
72 -deps --dependencies Includes a copy of the framework into the application
74 -d --directory=<value> Destination directory for installing the application.
75 -f --force Overwrite files that already exist. (false)
76 -h --help Show this help message.
77 -p --public_html=<value> Location where the application will be accesed by the
79 -q --quiet Suppress normal output. (false)
80 -s --skip Skip files that already exist. (false)
82 So running this command: (replace `/www/htdocs` with your web server public path. On some shared server it's `/home/USERNAME/public_html`)
84 ./script/setup -d HOMEDIR/booklink -p /www/htdocs/booklink
86 This will create the following structure for the **booklink** application:
89 app/ << The application including controllers, views, models and installers
90 config/ << Boring configuration files (will do the config via web)
91 public/ << This is the only folder made public under /www/htdocs/booklink softlink
92 script/ << Utils for code generation and running tests
94 **Note for Windows users:** A soft link to booklink/public is created only on *NIX systems, so you'll need to tell your web server where to find the public path for the **booklink** application on your `httpd.conf` file by adding something like this:
96 Alias /booklink "/path/to_your/booklink/public"
98 <Directory "/path/to_your/booklink/public">
99 Options Indexes FollowSymLinks
105 and then restart your web server.
107 ### Creating a database for your application ###
109 Next thing you'll need is to create a database for your application. If you intend to use SQLite on PHP5 skip this step.
111 Creating a MySQL database is out of the scope of this tutorial so you might need to google how to do this on your system or just try this common scenario where you can create 3 different databases one for each different environment (production, development and testing).
115 mysql> CREATE DATABASE booklink;
116 mysql> CREATE DATABASE booklink_dev;
117 mysql> CREATE DATABASE booklink_tests;
119 mysql> GRANT ALL ON booklink.* TO bermi@localhost IDENTIFIED BY "pass";
120 mysql> GRANT ALL ON booklink_dev.* TO bermi@localhost IDENTIFIED BY "pass";
121 mysql> GRANT ALL ON booklink_tests.* TO bermi@localhost IDENTIFIED BY "pass";
123 mysql> FLUSH PRIVILEGES;
126 If you are on a shared hosted server you might need to create it from your hosting provider control panel.
128 ### Generating the configuration file ###
130 #### Using the web installer ####
132 Now you can visit your application configuration wizard at http://localhost/booklink
134 Follow the steps in the wizard to set up your database, locales and file permissions and generate a configuration file. I'll go for a coffee while you do that so you can continue creating the **booklink** app.
136 #### Manual configuration editing ####
138 Save the files `config/DEFAULT-config.php` and `config/DEFAULT-routes.php` as `config/config.php` and `config/routes.php` and edit them following them as needed.
140 You might also need to set the base rewrite path manually if you want to be able to use nice URLs by editing the file `public/.htaccess` and setting RewriteBase like:
142 RewriteBase /booklink
144 After your application has been installed correctly you'll see a welcome message at http://localhost/booklink. Now you can safely remove the framework setup files (they won't be accessible if a `/config/config.php` file exists)
146 The booklink database structure
147 ---------------------------------
149 Now you need to define the tables and columns where your application will hold the information about books and authors.
151 When working with other developers database changes can be difficult to distribute among them. Akelos has a solution for this problem named *installer* or *migration*.
153 So you will create the database using an installer in order to distribute the changes you make to the booklink database scheme from time to time.
154 Using *installers* will also allow you to define your database tables and columns independently from the database vendor.
156 Now you will create a file named `app/installers/booklink_installer.php` with the following Installer code
160 class BooklinkInstaller extends AkInstaller
164 $this->createTable('books',
166 'title,'. // the title of the book
167 'description,'. // a description of the book
168 'author_id,'. // the author id. This is how Akelos will know how to link
169 'published_on' // the publication date
172 $this->createTable('authors',
174 'name' // the name of the author
179 $this->dropTables('books','authors');
185 That's enough for Akelos to create your database schema. If you just specify the column name, Akelos will default to the best data type based on database normalization conventions. If you want to have full control over your table settings, you can use [php Adodb Datadict syntax](http://phplens.com/lens/adodb/docs-datadict.htm)
187 Now we need to execute the installer with the command
189 ./script/migrate Booklink install
191 and that will do the trick. If we are using MySQL the database will look something like this:
195 +--------------+--------------+------+-----+----------------+
196 | Field | Type | Null | Key | Extra |
197 +--------------+--------------+------+-----+----------------+
198 | id | int(11) | NO | PRI | auto_increment |
199 | title | varchar(255) | YES | | |
200 | description | longtext | YES | | |
201 | author_id | int(11) | YES | MUL | |
202 | published_on | date | YES | | |
203 | updated_at | datetime | YES | | |
204 | created_at | datetime | YES | | |
205 +--------------+--------------+------+-----+----------------+
209 +--------------+--------------+------+-----+----------------+
210 | Field | Type | Null | Key | Extra |
211 +--------------+--------------+------+-----+----------------+
212 | id | int(11) | NO | PRI | auto_increment |
213 | name | varchar(255) | YES | | |
214 | updated_at | datetime | YES | | |
215 | created_at | datetime | YES | | |
216 +--------------+--------------+------+-----+----------------+
219 Models, Views and Controllers
220 ------------------------------------------------------
222 Akelos follows the [MVC design pattern](http://en.wikipedia.org/wiki/Model-view-controller) for organizing your application.
224 ![Akelos MVC diagram.](http://svn.akelos.org/trunk/docs/images/akelos_mvc.png)
226 ### Your application files and the Akelos Naming conventions ###
228 These are the conventions that empower the Akelos [convention over configuration](http://en.wikipedia.org/wiki/Convention_over_Configuration) philosophy.
232 * **Path:** /app/models/
233 * **Class Name:** singular, camel cased *(BankAccount, Person, Book)*
234 * **File Name:** singular, underscored *(bank_account.php, person.php, book.php)*
235 * **Table Name:** plural, underscored *(bank_accounts, people, books)*
237 #### Controllers ####
239 * **Path:** */app/controllers/*
240 * **Class Name:** singular or pural, camel cased, ends in `Controller` *(AccountController, PersonController)*
241 * **File Name:** singular or pural, underscored, ends in `_controller` *(`account_controller.php`, `person_controller.php`)*
245 * **Path:** /app/views/ + *underscored_controller_name/* *(app/views/person/)*
246 * **File Name:** action name, lowercase *(app/views/person/show.tpl)*
250 ------------------------------------------
252 Akelos comes with code generators that can cut your development time by creating fully functional [scaffold code](http://en.wikipedia.org/wiki/Scaffold_(programming)) that you can use as a departure/learning point.
254 ### Meet the Scaffold generator ###
256 You will generate a base skeleton for interacting with the **booklink** database created before. In order to get this skeleton quickly you can use the *scaffold generator* like this
258 ./script/generate scaffold Book
262 ./script/generate scaffold Author
264 This will generate a bunch of files and folders with code that really works!. Don't trust me? Try it yourself. Point your browser to [http://localhost/booklink/author](http://localhost/booklink/author) and [http://localhost/booklink/book](http://localhost/booklink/book) or to [http://localhost/booklink/?ak=author](http://localhost/booklink/?ak=author) and [http://localhost/booklink/?ak=book](http://localhost/booklink/?ak=book) in case mod_rewrite is disabled to start adding authors and books. Create some records and come back for an explanation of what is going under the hood.
268 ------------------------------------------
270 This is a small description of the workflow for a call to the following URL `http://localhost/booklink/book/show/2`
272 1. Akelos will break up your request into three parameters according to your `/config/routes.php` file (more on this later)
277 2. Once Akelos knows about this request it will look for the file `/app/controllers/book_controller.php` and if found it will instantiate the class `BookController`
279 3. The controller will look for a model that matches the parameter `controller` from the request. In this case it will look for `/app/models/book.php`. If found, it will create an instance of the model on the controller `$this->Book` attribute. If an `id` is on the request, it will search into the database for the Book with the id 2 and that will remain on `$this->Book`
281 4. Now it will call the action `show` from the `BookController` class if it's available.
283 5. Once the show action has been executed, the controller will look for the view file at `/app/views/book/show.tpl` and will render the results into the `$content_for_layout` variable.
285 6. Now Akelos will look for a layout named like the controller at `/app/views/layouts/book.tpl`. If found it will render the layout inserting `$content_for_layout` content and sending the output to the browser.
287 This might help you understanding the way Akelos handles your requests, so we are ready to modify the base application.
290 Relating Books and Authors
291 ----------------------------
293 Now you are going to link authors and books (complex associations in upcoming tutorials). In order to achieve this you will use the `author_id` column you added to your database.
295 So you will need to tell your models how they relate to each other like
297 */app/models/book.php*
301 class Book extends ActiveRecord
303 var $belongs_to = 'author'; // <- declaring the association
308 */app/models/author.php*
312 class Author extends ActiveRecord
314 var $has_many = 'books'; // <- declaring the association
319 Now that you made the models aware of each other you will need to modify the book controller so it loads the `author` and the `book` model instances
321 */app/controllers/book_controller.php*
325 class BookController extends ApplicationController
327 var $models = 'book, author'; // <- make these models available
329 // ... more BookController code
333 // Replace "$this->book = $this->Book->find(@$this->params['id']);"
334 // with this in order to find related authors.
335 $this->book = $this->Book->find(@$this->params['id'], array('include' => 'author'));
338 // ... more BookController code
341 Next step is to show available authors when creating or editing a book. This can be achieved using the `$form_options_helper` by inserting the following code
342 right after `<?=$active_record_helper->error_messages_for('book');?>` on the */app/views/book/_form.tpl* file
345 <label for="author">_{Author}</label><br />
346 <?=$form_options_helper->select('book', 'author_id', $Author->collect($Author->find(), 'name', 'id'));?>
349 If you have not added authors yet, go and create some right now and then visit http://locahost/booklink/book/add to check out the brand new authors select list. Go ahead and create a new book selecting an author from the list.
351 Seems like the author has been saved but it its not included on the `app/views/book/show.tpl` view. You'll add it this code right after `<? $content_columns = array_keys($Book->getContentColumns()); ?>`
353 <label>_{Author}:</label> <span class="static">{book.author.name?}</span><br />
355 The final step - show the author in the listing. In order to do it replace the last string of the listing method in book_controller.php with the following text:
357 $find_options = $this->pagination_helper->getFindOptions($this->Book);
358 $find_options['include'] = 'author';
359 $this->books =& $this->Book->find('all', $find_options);
361 Now we can edit `app/views/book/listing.tpl`:
362 * insert new string `<th>_{Author}</th>` right before `<?php $content_columns = array_keys($Book->getContentColumns()); ?>`
363 * Make the template to output author'a name by adding `<td>{post.user.login?}</td>` after `<tr {?post_odd_position}class="odd"{end}>`
365 You must be screaming now about the rare `_{Author}` and `{book.author.name?}` syntax. Thats actually [Sintags](http://www.bermi.org/projects/sintags) a small set of rules that helps on writing cleaner views and that will be compiled to standard PHP.
371 This is all for now, I'll be improving this tutorial from time to time to add some missing features to this and other documents like:
386 My apologies for any typo or grammatical error you might find. English is not my mother tongue and I would really like you to help me [improving and fixing errors in this document](http://trac.akelos.org/newticket?keywords=booklink%20english&component=Documentation&priority=minor&type=documentation&summary=Booklin%20Tutorial%20improvements).