akelos vs cakephp

Introduction

CakePHP is a rapid development framework for PHP which uses commonly known design patterns like ActiveRecord, Association Data Mapping, Front Controller and MVC. Our primary goal is to provide a structured framework that enables PHP users at all levels to rapidly develop robust web applications, without any loss to flexibility.

-CakePHPAkelos
Latest version1.2.0.58750.8
PHP4CakePHP Support PHP4Akelos Support PHP4
PHP5CakePHP Support PHP5Akelos Support PHP5
MVCCakePHP Support MVCAkelos Support MVC
Multiple DBCakePHP Support Multiple DBAkelos Support Multiple DB
ORMCakePHP Support ORMAkelos Support ORM
DB ObjectsCakePHP Support DB ObjectsAkelos Support DB Objects
Templates-Akelos Support Templates
CachingCakePHP Support CachingAkelos Support Caching
ValidationCakePHP Support ValidationAkelos Support Validation
AjaxCakePHP Support AjaxAkelos Support Ajax
Auth ModuleCakePHP Support Auth ModuleAkelos Support Auth Module
ModulesCakePHP Support ModulesAkelos Support Modules
CostFreeFree
Official websitehttp://www.cakephp.orghttp://www.akelos.org/
Download URLhttp://cakephp.org/downloadshttp://www.akelos.org/download
Manual URLhttp://manual.cakephp.org/http://www.akelos.org/docs
Installation
Section 1

Introduction

So now you know everything there is to know about the structure and purpose of all the CakePHP libraries, or you have skipped to this part because you don't care about that stuff and just want to start playing. Either way, you're ready to get your hands dirty.

This chapter will describe what must be installed on the server, different ways to configure your server, downloading and installing CakePHP, bringing up the default CakePHP page, and some troubleshooting tips just in case everything does not go as planned.

Section 2

Requirements

In order use CakePHP you must first have a server that has all the required libraries and programs to run CakePHP:

Server Requirements

Here are the requirements for setting up a server to run CakePHP:

 

  1. An HTTP server (like Apache) with the following enabled: sessions, mod_rewrite (not absolutely necessary but preferred)

  2. PHP 4.3.2 or greater. Yes, CakePHP works great in either PHP 4 or 5.

  3. A database engine (right now, there is support for MySQL 4+, PostgreSQL and a wrapper for ADODB).

Section 3

Installing CakePHP

Getting the most recent stable version

There are a few ways you can secure a copy of CakePHP: getting a stable release from CakeForge, grabbing a nightly build, or getting a fresh version of code from SVN.

To download a stable version of code, check out the files section of the CakePHP project at CakeForge by going tohttp://cakeforge.org/projects/cakephp/.

To grab a nightly, download one fromhttp://cakephp.org/downloads/index/nightly. These nightly releases are stable, and often include the bug fixes between stable releases.

To grab a fresh copy from our SVN repository, use your favorite SVN client and connect to https://svn.cakephp.org/repo/trunk/cake/ and choose the version you're after.

Unpacking

Now that you've downloaded the most recent release, place that compressed package on your web server in the webroot. Now you need to unpack the CakePHP package. There are two ways to do this, using a development setup, which allows you to easily view many CakePHP applications under a single domain, or using the production setup, which allows for a single CakePHP application on the domain.

Section 4

Setting Up CakePHP

The first way to setup CakePHP is generally only recommended for development environments because it is less secure. The second way is considered more secure and should be used in a production environment.

NOTE: /app/tmp must be writable by the user that your web server runs as.

Development Setup

For development we can place the whole Cake installation directory inside the specified DocumentRoot like this:

 

/wwwroot
    /cake
        /app
        /cake
        /vendors
        .htaccess
        index.php

In this setup the wwwroot folder acts as the web root so your URLs will look something like this (if you're also using mod_rewrite):

 

www.example.com/cake/controllerName/actionName/param1/param2

Production Setup

In order to utilize a production setup, you will need to have the rights to change the DocumentRoot on your server. Doing so, makes the whole domain act as a single CakePHP application.

The production setup uses the following layout:

../path_to_cake_install
    /app
        /config
        /controllers
        /models
        /plugins
        /tmp
        /vendors
        /views
        /webroot <-- This should be your new DocumentRoot
        .htaccess
        index.php
    /cake
    /vendors
    .htaccess
    index.php

 

Suggested Production httpd.conf

DocumentRoot /path_to_cake/app/webroot

 

In this setup the webroot directory is acting as the web root so your URLs might look like this (if you're using mod_rewrite):

http://www.example.com/controllerName/actionName/param1/param2

 

Advanced Setup: Alternative Installation Options

There are some cases where you may wish to place Cake's directories on different places on disk. 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.

There are three main parts to a Cake application:

  1. The core CakePHP libraries - Found in /cake

  2. Your application code (e.g. controllers, models, layouts and views) - Found in /app

  3. Your application webroot files (e.g. images, javascript and css) - Found 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 (as it is distributed in Cake). There are three constants that you'll need to edit: ROOT, APP_DIR, and CAKE_CORE_INCLUDE_PATH.

  1. ROOT should be set to the path of the directory that contains yourapp folder.

  2. APP_DIR should be set to the path of your app folder.

  3. CAKE_CORE_INCLUDE_PATH should be set to the path of your Cake libraries folder.

/app/webroot/index.php (partial, comments removed)

if (!defined('ROOT'))
{
    define('ROOT', dirname(dirname(dirname(__FILE__))));
}

if (!defined('APP_DIR'))
{
    define ('APP_DIR', basename(dirname(dirname(__FILE__))));
}

if (!defined('CAKE_CORE_INCLUDE_PATH'))
{
    define('CAKE_CORE_INCLUDE_PATH', ROOT);
}

An example might help illustrate this better. Imagine that I wanted to set up Cake to work with the following setup:

  1. I want my Cake libraries shared with other applications, and placed in /usr/lib/cake.

  2. My Cake webroot directory needs to be /var/www/mysite/.

  3. My application files will be stored in /home/me/mysite.

Here's what the file setup looks like:

/home
    /me
        /mysite                  <-- Used to be /cake_install/app
            /config
            /controllers
            /models
            /plugins
            /tmp
            /vendors
            /views
            index.php
/var
    /www
        /mysite                  <-- Used to be /cake_install/app/webroot
            /css
            /files
            /img
            /js
            .htaccess
            css.php
            favicon.ico
            index.php
/usr
    /lib
        /cake                    <-- Used to be /cake_install/cake
            /cake
                /config
                /docs
                /libs
                /scripts
                app_controller.php
                app_model.php
                basics.php
                bootstrap.php
                dispatcher.php
            /vendors
 

Given this type of setup, I would need to edit my webroot index.php file (which should be at /var/www/mysite/index.php, in this example) to look like the following:

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.

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');
}
Section 5

Configuring Apache and mod_rewrite

While CakePHP is built to work with mod_rewrite out of the box, 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:

  1. Make sure that an .htaccess override is allowed: in your httpd.conf, you should have a section that defines a section for each Directory on your server. Make sure the AllowOverride is set to All for the correct Directory.

  2. Make sure you are editing the system httpd.conf rather than a user- or site-specific httpd.conf.

  3. For some reason or another, you might have obtained a copy of CakePHP without the needed .htaccess files. This sometimes happens because some operating systems treat files that start with '.' as hidden, and don't copy them. Make sure your copy of CakePHP is from the downloads section of the site or our SVN repository.

  4. Make sure you are loading up mod_rewrite correctly! You should see something like LoadModule rewrite_module libexec/httpd/mod_rewrite.so and AddModule mod_rewrite.c in your httpd.conf.

  5. If you are installing Cake into a user directory (http://example.com/~myusername/), you'll need to modify the .htaccess files in the base directory of your Cake installation, and in the app/webroot folder. Just add the line "RewriteBase /~myusername/".

  6. If for some reason your URLS are suffixed with a long, annoying session ID (http://example.com/posts/?CAKEPHP=4kgj577sgabvnmhjgkdiuy1956if6ska), you might also add "php_flag session.trans_id off" to the .htaccess file at the root of your installation as well.

Section 6

Make Sure It's Working

Alright, lets see this baby in action. Depending on which setup you used, you should point your browser to http://www.example.com or http://www.example.com/cake. 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 Cake-based application.

Setting up a new Akelos application

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)

Now you can follow two paths:

  1. Create an Akelos application in a different folder and link it to the Framework libraries.
  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.

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.

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

./script/setup -h

which will show us available options for the installer

Usage: setup [-sqphf --dependencies] <-d> 

-deps --dependencies      Includes a copy of the framework into the application
                          directory. (true)
-d --directory=<value>    Destination directory for installing the application.
-f --force                Overwrite files that already exist. (false)
-h --help                 Show this help message.
-p --public_html=<value>  Location where the application will be accesed by the
                          webserver. ()
-q --quiet                Suppress normal output. (false)
-s --skip                 Skip files that already exist. (false)

So running this command: (replace /www/htdocs with your web server public path. On some shared server it's/home/USERNAME/public_html)

./script/setup -d HOMEDIR/booklink -p /www/htdocs/booklink

This will create the following structure for the booklink application:

booklink/
    app/ << The application including controllers, views, models and installers
    config/ << Boring configuration files (will do the config via web)
    public/ << This is the only folder made public under /www/htdocs/booklink softlink
    script/ << Utils for code generation and running tests

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:

Alias /booklink "/path/to_your/booklink/public"

<Directory "/path/to_your/booklink/public">
    Options Indexes FollowSymLinks
    AllowOverride All
    Order allow,deny
    Allow from all
</Directory>

and then restart your web server.

Creating a database for your application

Next thing you'll need is to create a database for your application. If you intend to use SQLite on PHP5 skip this step.

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).

mysql -u root -p

mysql> CREATE DATABASE booklink;
mysql> CREATE DATABASE booklink_dev;
mysql> CREATE DATABASE booklink_tests;

mysql> GRANT ALL ON booklink.* TO bermi@localhost IDENTIFIED BY "pass";
mysql> GRANT ALL ON booklink_dev.* TO bermi@localhost IDENTIFIED BY "pass";
mysql> GRANT ALL ON booklink_tests.* TO bermi@localhost IDENTIFIED BY "pass";

mysql> FLUSH PRIVILEGES;
mysql> exit

If you are on a shared hosted server you might need to create it from your hosting provider control panel.

Generating the configuration file

Using the web installer

Now you can visit your application configuration wizard at http://localhost/booklink

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.

Manual configuration editing

Save the files config/DEFAULT-config.php and config/DEFAULT-routes.php as config/config.php andconfig/routes.php and edit them following them as needed.

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:

RewriteBase /booklink

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)

The booklink database structure

Now you need to define the tables and columns where your application will hold the information about books and authors.

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.

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. Using installers will also allow you to define your database tables and columns independently from the database vendor.

Now you will create a file named app/installers/booklink_installer.php with the following Installer code

 <?php

 class BooklinkInstaller extends AkInstaller
 {
     function up_1(){

         $this->createTable('books',
            'id,'.          // the key
            'title,'.       // the title of the book
            'description,'. // a description of the book
            'author_id,'.   // the author id. This is how Akelos will know how to link
            'published_on'  // the publication date
        );

         $this->createTable('authors', 
            'id,'.      // the key
            'name'      // the name of the author
            );
     }

     function down_1(){
         $this->dropTables('books','authors');
     }
 }

 ?>

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

Now we need to execute the installer with the command

./script/migrate Booklink install

and that will do the trick. If we are using MySQL the database will look something like this:

BOOKS TABLE

+--------------+--------------+------+-----+----------------+
| Field        | Type         | Null | Key | Extra          |
+--------------+--------------+------+-----+----------------+
| id           | int(11)      | NO   | PRI | auto_increment |
| title        | varchar(255) | YES  |     |                |
| description  | longtext     | YES  |     |                |
| author_id    | int(11)      | YES  | MUL |                |
| published_on | date         | YES  |     |                |
+--------------+--------------+------+-----+----------------+ 

AUTHORS TABLE

+-------+--------------+------+-----+----------------+
| Field | Type         | Null | Key | Extra          |
+-------+--------------+------+-----+----------------+
| id    | int(11)      | NO   | PRI | auto_increment |
| name  | varchar(255) | YES  |     |                |
+-------+--------------+------+-----+----------------+

Models, Views and Controllers

Akelos follows the MVC design pattern for organizing your application.

Akelos MVC diagram.

Your application files and the Akelos Naming conventions

These are the conventions that empower the Akelos convention over configuration philosophy.

Models
  • Path: /app/models/
  • Class Name: singular, camel cased (BankAccount, Person, Book)
  • File Name: singular, underscored (bank_account.php, person.php, book.php)
  • Table Name: plural, underscored (bank_accounts, people, books)
Controllers
  • Path: /app/controllers/
  • Class Name: singular or pural, camel cased, ends in Controller (AccountController, PersonController)
  • File Name: singular or pural, underscored, ends in _controller (account_controller.php,person_controller.php)
Views
  • Path: /app/views/ + underscoredcontrollername/ (app/views/person/)
  • File Name: action name, lowercase (app/views/person/show.tpl)

Akelos scaffolding

Akelos comes with code generators that can cut your development time by creating fully functional scaffold code that you can use as a departure/learning point.

Meet the Scaffold generator

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

./script/generate scaffold Book

and

./script/generate scaffold Author

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 and http://localhost/booklink/books to start adding authors and books. Create some records and come back for an explanation of what is going under the hood.

The Akelos Workflow

This is a small description of the workflow for a call to the following URL http://localhost/booklink/book/show/2

  1. Akelos will break up your request into three parameters according to your /config/routes.php file (more on this later)

    • controller: book
    • action: show
    • id: 2
  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

  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

  4. Now it will call the action show from the BookController class if it's available.

  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.

  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.

This might help you understanding the way Akelos handles your requests, so we are ready to modify the base application.

Relating Books and Authors

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.

So you will need to tell your models how they relate to each other like

/app/models/book.php

<?php

class Book extends ActiveRecord
{
    var $belongs_to = 'author'; // <- declaring the association
}

?>

/app/models/author.php

<?php

class Author extends ActiveRecord
{
    var $has_many = 'books'; // <- declaring the association
}

?>

Now that you made the models aware of each other you will need to modify the book controller so it loads theauthor and the book model instances

/app/controllers/book_controller.php

<?php

class BookController extends ApplicationController
{
    var $models = 'book, author'; // <- make these models available

    // ... more BookController code

    function show()
    {
        // Replace "$this->book = $this->Book->find(@$this->params['id']);"
        // with this in order to find related authors.
        $this->book = $this->Book->find(@$this->params['id'], array('include' => 'author'));
    }

    // ... more BookController code
}

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 right after <?=$active_record_helper->error_messages_for('book');?> on the /app/views/book/_form.tpl file

<p>
    <label for="author">_{Author}</label><br />

    <?=$form_options_helper->select('book', 'author_id', $Author->collect($Author->find(), 'name', 'id'));?>
</p>

If you have not added authors yet, go and created some right now and then visit http://locahost/boolink/book/add to check out the brand new authors select list. Go ahead and create a new book selecting an author from the list.

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()); ?>

<label>_{Author}:</label> <span class="static">{book.author.name?}</span><br />

You must be screaming now about the rare _{Author} and {book.author.name?} syntax. Thats actually Sintags a small set of rules that helps on writing cleaner views and that will be compiled to standard PHP.

Colophon

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:

  • validations
  • routes
  • filters
  • callbacks
  • transactions
  • console
  • AJAX
  • helpers
  • web services
  • testing
  • distributing
  • and many more...

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.

System Requirements

Requirements

In order use CakePHP you must first have a server that has all the required libraries and programs to run CakePHP:

Server Requirements

Here are the requirements for setting up a server to run CakePHP:

 

  1. An HTTP server (like Apache) with the following enabled: sessions, mod_rewrite (not absolutely necessary but preferred)

  2. PHP 4.3.2 or greater. Yes, CakePHP works great in either PHP 4 or 5.

  3. A database engine (right now, there is support for MySQL 4+, PostgreSQL and a wrapper for ADODB).

 

  • A MySQL or SQLite Database
  • Apache web server
  • Shell access to your server
  • PHP4 or PHP5

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值