8 Great CSS Frameworks

Posted on June 26th, 2008 in Frameworks, HTML by Ashish  Tagged ,

Well, I guess I’m going to work backwords. There are three layers to the frontend; behaviour, presentation and markup. We’ve done behavior so we’re onto presentational now. CSS Frameworks have been all the buzz lately, we’ve had ones that use python ways of code then regenerate it as css, ones that are specifically for forms and an awesome one which is just for styling print!

Personally I find frameworks to much hassle, I have my own little framework but that is only really 20 or so lines. I might share it with all of you in the coming weeks if you would like it. Now here they are!

1. 960 Grid System - The 960 Grid System is an effort to streamline web development workflow by providing commonly used dimensions, based on a width of 960 pixels. There are two variants: 12 and 16 columns, which can be used separately or in tandem.

2. Blueprint CSS - Blueprint is a CSS framework, which aims to cut down on your CSS development time. It gives you a solid CSS foundation to build your project on top of, with an easy-to-use grid, sensible typography, and even a stylesheet for printing.

3. Hartija – The owner of Hartija describes it as a “universal Cascading Style Sheets for web printing”. It’s extremely customizable and very user friendly.

4. Formy CSS – Formy is mini CSS Framework for building web forms.

5. Clever CSS – CleverCSS is a small markup language for CSS inspired by Python that can be used to build a style sheet in a clean and structured way. In many ways it’s cleaner and more powerful than CSS2 is.

6. SenCSS – SenCSS is a sensible standards CSS Framework. This means that SenCSS tries to supply standard styling for all repetitive parts of your CSS, allowing you to focus on the fun parts. In that sense, senCSS is a bit like a large CSS Reset.

7. Elements -

Elements is a down to earth CSS framework. It was built to help designers write CSS faster and more efficient. Elements goes beyond being just a framework, it’s its own project workflow.It has everything you need to complete your project, which makes you and your clients happy. Read the Overview for more information.

8. LogicCSS – The Logic CSS framework is a collection of CSS files and PHP utilities to cut development times for web-standards compliant xHTML layouts.

This is just the tip of the iceberg, there are tones more css frameworks out there. I plan on releasing one for this site.

CakePHP Naming Conventions, Global Constants, Global Functions

Posted on March 3rd, 2008 in Frameworks by Ashish  Tagged , , ,

config (’file_name’)

Global Functions

up (’string’) r (’search’, ‘replace’, ‘text’) pr (array) am (array, [array, array]) env (’HTTP_HEADER’)

cache (path, data, expires, [target])

Models

Class Name: singular, camel cased (LineItem, Person) File Name: singular, underscored (line_item.php, person.php) Table Name: plural, underscored (line_items, people)

Controllers

Class Name: plural, camel cased, ends in "Controller"

Views

Path: controller name, underscored (app/views/line_items/<file>, app/ views/people/<file>) File Name: action name, lowercase (index.thtml, view.thtml)

uses (’file_name’) vendor (’file_name’) debug (’message’) a (element, [element, element]) aa (key, value, [key, value]) e (’message’) low (’STRING’)

(LineItemsController, People Controller)

File Name: plural, underscored

(line_items_controller.php, people_controller.php)

clearCache ([params, type, ext]) countdim (array)

Model

Properties $cacheQueries $data $displayField $id $name $primaryKey Methods $recursive $useDbConfig $useTable $validate $validationErrors $_tableInfo Association Properties $belongsTo $hasAndBelongsToMany $hasMany $hasOne

Controller

Properties $name $autoLayout $base $cacheAction $data $here $output $params $plugin $view $webroot Methods $action $autoRender $beforeFilter $components $helpers $layout $pageTitle $persistModel $uses $viewPath Properties $action $autoRender $controller $hasRendered $here $loaded $name $params $plugin $themeWeb $viewPath Methods

View

$autoLayout $base $ext $helpers $layout $models $pageTitle $parent $subDir $uses

bindModel (params) create ( ) delete (id, [cascade]) escapeField (field) execute (data) exists ( ) field (name, conditions, order) find ([conditions, fields, order, recursive])

findAll ([conditions, fields, order, limit, page, recur...])

getLastInsertID ( ) getNumRows ( ) hasAny ([conditions]) hasField (name) invalidate (field) invalidFields ([data]) isForeignKey (field) loadInfo ( ) query ([sql]) read ([fields, id]) remove ([id, cascade]) save ([data, validate, fieldList]) saveField ([name, value, validate]) set (one, [two]) setDataSource (dataSource) setSource (tableName) unbindModel (params) validates ([data])

findAllThreaded([conditions, fields, sort]) findCount ([conditions, recursive]) findNeighbours (conditions, field, value)

generateList ([conditions, order, limit, keyPath, val...])

getAffectedRows ( ) getColumnType (column) getColumnTypes ( ) getDisplayField ( ) getID ([list])

cleanUpFields ( ) constructClasses ( ) flash (message, url, [pause]) flashOut (message, url, [pause]) generateFieldNames (data, doCreateO…) postConditions (data) redirect (url, [status]) referer ([default, local]) render([action, layout, file]) set (one, [two]) setAction (action, [param, param, param]) validate ( ) validateErrors ( )

element (name) error (code, name, message) pluginView (action, layout) render ([action, layout, file]) renderCache (filename, timeStart) renderElement (name, [params]) renderLayout (content_for_layout) setLayout (layout)

Helper

Availability: View only

Callbacks afterDelete ( ) beforeDelete ( ) beforeFind (&qu..) afterFind (results)

beforeSave ( ) beforeValidate ( )

afterSave ( )

Callbacks beforeFilter ( ) afterFilter ( )

beforeRender ( )

Global Constants

Core Defines

ACL_CLASSNAME ACL_FILENAME AUTO_SESSION CACHE_CHECK CAKE_ADMIN CAKE_SECURITY

CAKE_SESSION_COOKIE

CAKE_SESSION_STRING

Paths

APP APP_DIR APP_PATH CACHE CAKE COMPONENTS CONFIGS CONTROLLER_TESTS CONTROLLERS CSS ELEMENTS HELPER_TESTS HELPERS

Component

INFLECTIONS JS LAYOUTS LIB_TESTS LIBS LOGS MODEL_TESTS MODELS SCRIPTS TESTS TMP VENDORS VIEWS Availability: Controller / View

CAKE_SESSION_TABLE

CAKE_SESSION_TIMEOUT

Properties

$disableStartup

COMPRESS_CSS DEBUG LOG_ERROR MAX_MD5SIZE WEBSERVICES

Callbacks

startup (&controller)

Properties $tags $base $here $action $themeWeb $view $webroot $params $data $plugin Callbacks

afterRender ( )

CAKE_SESSION_SAVE

Conventions

Class Name: MyCoolComponent

Path: app/controllers/components/my_cool.php

Conventions

Class Name: MyCoolHelper Path: app/views/helpers/my_cool.php

Webroot Configurable Paths

CORE_PATH ROOT WWW_ROOT WEBROOT_DIR

Usage

Controller: $this->MyCool->method( ); View: $this->controller->MyCool->method( );

Usage

View: $myCool->method( );

CAKE_CORE_INCLUDE_PATH

 

Download CakeSheet Pdf for complete reference.

 

symfony Open-Source PHP Web Framework

Posted on February 19th, 2008 in Frameworks by Ashish  Tagged , , ,

Symfony in Brief

A framework streamlines application development by automating many of the patterns employed for a given purpose. A framework also adds structure to the code, prompting the developer to write better, more readable, and more maintainable code. Ultimately, a framework makes programming easier, since it packages complex operations into simple statements.

Symfony is a complete framework designed to optimize the development of web applications by way of several key features. For starters, it separates a web application’s business rules, server logic, and presentation views. It contains numerous tools and classes aimed at shortening the development time of a complex web application. Additionally, it automates common tasks so that the developer can focus entirely on the specifics of an application. The end result of these advantages means there is no need to reinvent the wheel every time a new web application is built!

Symfony was written entirely in PHP 5. It has been thoroughly tested in various real-world projects, and is actually in use for high-demand e-business websites. It is compatible with most of the available databases engines, including MySQL, PostgreSQL, Oracle, and Microsoft SQL Server. It runs on *nix and Windows platforms. Let’s begin with a closer look at its features.

Symfony Features

Symfony was built in order to fulfill the following requirements:

* Easy to install and configure on most platforms (and guaranteed to work on standard *nix and Windows platforms)
* Database engine-independent
* Simple to use, in most cases, but still flexible enough to adapt to complex cases
* Based on the premise of convention over configuration–the developer needs to configure only the unconventional
* Compliant with most web best practices and design patterns
* Enterprise-ready–adaptable to existing information technology (IT) policies and architectures, and stable enough for long-term projects
* Very readable code, with phpDocumentor comments, for easy maintenance
* Easy to extend, allowing for integration with other vendor libraries

Automated Web Project Features

Most of the common features of web projects are automated within symfony, as follows:

* The built-in internationalization layer allows for both data and interface translation, as well as content localization.
* The presentation uses templates and layouts that can be built by HTML designers without any knowledge of the framework. Helpers reduce the amount of presentation code to write by encapsulating large portions of code in simple function calls.
* Forms support automated validation and repopulation, and this ensures a good quality of data in the database and a better user experience.
* Output escaping protects applications from attacks via corrupted data.
* The cache management features reduce bandwidth usage and server load.
* Authentication and credential features facilitate the creation of restricted sections and user security management.
* Routing and smart URLs make the page address part of the interface and search-engine friendly.
* Built-in e-mail and API management features allow web applications to go beyond the classic browser interactions.
* Lists are more user-friendly thanks to automated pagination, sorting, and filtering.
* Factories, plug-ins, and mixins provide a high level of extensibility.
* Ajax interactions are easy to implement thanks to one-line helpers that encapsulate cross-browser-compatible JavaScript effects.

Development Environment and Tools

To fulfill the requirements of enterprises having their own coding guidelines and project management rules, symfony can be entirely customized. It provides, by default, several development environments and is bundled with multiple tools that automate common software-engineering tasks:

* The code-generation tools are great for prototyping and one-click back-end administration.
* The built-in unit and functional testing framework provides the perfect tools to allow test-driven development.
* The debug panel accelerates debugging by displaying all the information the developer needs on the page he’s working on.
* The command-line interface automates application deployment between two servers.
* Live configuration changes are possible and effective.
* The logging features give administrators full details about an application’s activities.

Who Made Symfony and Why?

The first version of symfony was released in October 2005 by project founder Fabien Potencier, coauthor of this book. Fabien is the CEO of Sensio (http://www.sensio.com/), a French web agency well known for its innovative views on web development.

Back in 2003, Fabien spent some time inquiring about the existing open source development tools for web applications in PHP. He found that none fulfilled the previously described requirements. When PHP 5 was released, he decided that the available tools had reached a mature enough stage to be integrated into a full-featured framework. He subsequently spent a year developing the symfony core, basing his work on the Mojavi Model-View-Controller (MVC) framework, the Propel object-relational mapping (ORM), and the Ruby on Rails templating helpers.

Fabien originally built symfony for Sensio’s projects, because having an effective framework at your disposal presents an ideal way to develop applications faster and more efficiently. It also makes web development more intuitive, and the resulting applications are more robust and easier to maintain. The framework entered the proving grounds when it was employed to build an e-commerce website for a lingerie retailer, and subsequently was applied to other projects.

After successfully using symfony for a few projects, Fabien decided to release it under an open source license. He did so to donate this work to the community, to benefit from user feedback, to showcase Sensio’s experience, and because it’s fun.

Why "symfony" and not "FooBarFramework"? Because Fabien wanted a short name containing an s, as in Sensio, and an f, as in framework–easy to remember and not associated with another development tool. Also, he doesn’t like capital letters. symfony was close enough, even if not completely English, and it was also available as a project name. The other alternative was "baguette."

For symfony to be a successful open source project, it needed to have extensive documentation, in English, to increase the adoption rate. Fabien asked fellow Sensio employee François Zaninotto, the other author of this book, to dig into the code and write an online book about it. It took quite a while, but when the project was made public, it was documented well enough to appeal to numerous developers. The rest is history.

The Symfony Community

As soon as the symfony website (http://www.symfony-project.org/) was launched, numerous developers from around the world downloaded and installed the framework, read the online documentation, and built their first application with symfony, and the buzz began to mount.

Web application frameworks were getting popular at that time, and the need for a full-featured framework in PHP was high. Symfony offered a compelling solution due to its impressive code quality and significant amount of documentation–two major advantages over the other players in the framework category. Contributors soon began to surface, proposing patches and enhancements, proofreading the documentation, and performing other much-needed roles.

The public source repository and ticketing system offer a variety of ways to contribute, and all volunteers are welcome. Fabien is still the main committer in the trunk of the source code repository, and guarantees the quality of the code.

Today, the symfony forum, mailing lists, and Internet Relay Chat (IRC) channel offer ideal support outlets, with seemingly each question getting an average of four answers. Newcomers install symfony every day, and the wiki and code snippets sections host a lot of user-contributed documentation. The number of known symfony applications increases by an average of five per week, and counting.

Is Symfony for Me?

Whether you are a PHP 5 expert or a newcomer to web application programming, you will be able to use symfony. The main factor in deciding whether or not to do so is the size of your project.

If you want to develop a simple website with five to ten pages, limited access to a database, and no obligations to ensuring its performance or providing documentation, then you should stick with PHP alone. You wouldn’t gain much from a web application framework, and using object orientation or an MVC model would likely only slow down your development process. As a side note, symfony is not optimized to run efficiently on a shared server where PHP scripts can run only in Common Gateway Interface (CGI) mode.

On the other hand, if you develop more complex web applications, with heavy business logic, PHP alone is not enough. If you plan on maintaining or extending your application in the future, you will need your code to be lightweight, readable, and effective. If you want to use the latest advances in user interaction (like Ajax) in an intuitive way, you can’t just write hundreds of lines of JavaScript. If you want to have fun and develop fast, then PHP alone will probably be disappointing. In all these cases, symfony is for you.

And, of course, if you are a professional web developer, you already know all the benefits of web application frameworks, and you need one that is mature, well documented, and has a large community. Search no more, for symfony is your solution.

If you would like a visual demonstration, take a look at the screencasts available from the symfony website. You will see how fast and fun it is to develop applications with symfony.

Fundamental Concepts

Before you get started with symfony, you should understand a few basic concepts. Feel free to skip ahead if you already know the meaning of OOP, ORM, RAD, DRY, KISS, TDD, YAML, and PEAR.

PHP 5

Symfony is developed in PHP 5 (http://www.php.net/) and dedicated to building web applications with the same language. Therefore, a solid understanding of PHP 5 is required to get the most out of the framework.

Developers who already know PHP 4 but not PHP 5 should mainly focus on the language’s new object-oriented model.

Object-Oriented Programming (OOP)

Object-oriented programming (OOP) will not be explained in this chapter. It needs a whole book itself! Because symfony makes extensive use of the object-oriented mechanisms available as of PHP 5, OOP is a prerequisite to learning symfony.

Wikipedia explains OOP as follows:

The idea behind object-oriented programming is that a computer program may be seen as comprising a collection of individual units, or objects, that act on each other, as opposed to a traditional view in which a program may be seen as a collection of functions, or simply as a list of instructions to the computer.

PHP 5 implements the object-oriented paradigms of class, object, method, inheritance, and much more. Those who are not familiar with these concepts are advised to read the related PHP documentation, available at http://www.php.net/manual/en/language.oop5.basic.php.
Magic Methods

One of the strengths of PHP’s object capabilities is the use of magic methods. These are methods that can be used to override the default behavior of classes without modifying the outside code. They make the PHP syntax less verbose and more extensible. They are easy to recognize, because the names of the magic methods start with two underscores (__).

For instance, when displaying an object, PHP implicitly looks for a __toString() method for this object to see if a custom display format was defined by the developer:

$myObject = new myClass();
echo $myObject;
// Will look for a magic method
echo $myObject->__toString();

Symfony uses magic methods, so you should have a thorough understanding of them. They are described in the PHP documentation (http://www.php.net/manual/en/language.oop5.magic.php).

PHP Extension and Application Repository (PEAR)

PEAR is "a framework and distribution system for reusable PHP components." PEAR allows you to download, install, upgrade, and uninstall PHP scripts. When using a PEAR package, you don’t need to worry about where to put scripts, how to make them available, or how to extend the command-line interface (CLI).

PEAR is a community-driven project written in PHP and shipped with standard PHP distributions.

The PEAR website, http://pear.php.net/, provides documentation and packages grouped by categories.

PEAR is the most professional way to install vendor libraries in PHP. Symfony advises the use of PEAR to keep a central installation point for use across multiple projects. The symfony plug-ins are PEAR packages with a special configuration. The symfony framework itself is available as a PEAR package.

You don’t need to know all about the PEAR syntax to use symfony. You just need to understand what it does and have it installed. You can check that PEAR is installed in your computer by typing the following in a CLI:

> pear info pear

This command will return the version number of your PEAR installation.

The symfony project has its own PEAR repository, or channel. Note that channels are available only since version 1.4.0 of PEAR, so you should upgrade if your version is older. To upgrade your version of PEAR, issue the following command:

> pear upgrade PEAR

Object-Relational Mapping (ORM)

Databases are relational. PHP 5 and symfony are object-oriented. In order to access the database in an object-oriented way, an interface translating the object logic to the relational logic is required. This interface is called an object-relational mapping, or ORM.

An ORM is made up of objects that give access to data and keep business rules within themselves.

One benefit of an object/relational abstraction layer is that it prevents you from using a syntax that is specific to a given database. It automatically translates calls to the model objects to SQL queries optimized for the current database.

This means that switching to another database system in the middle of a project is easy. Imagine that you have to write a quick prototype for an application, but the client has not decided yet which database system would best suit his needs. You can start building your application with SQLite, for instance, and switch to MySQL, PostgreSQL, or Oracle when the client is ready to decide. Just change one line in a configuration file, and it works.

An abstraction layer encapsulates the data logic. The rest of the application does not need to know about the SQL queries, and the SQL that accesses the database is easy to find. Developers who specialize in database programming also know clearly where to go.

Using objects instead of records, and classes instead of tables, has another benefit: you can add new accessors to your tables. For instance, if you have a table called Client with two fields, FirstName and LastName, you might like to be able to require just a Name. In an object-oriented world, this is as easy as adding a new accessor method to the Client class, like this:

public function getName()
{
return $this->getFirstName().’ ‘.$this->getLastName();
}

All the repeated data-access functions and the business logic of the data can be maintained within such objects. For instance, consider a class ShoppingCart in which you keep items (which are objects). To retrieve the full amount of the shopping cart for the checkout, you can add a getTotal() method, like this:

public function getTotal()
{
$total = 0;
foreach ($this->getItems() as $item)
{
$total += $item->getPrice() * $item->getQuantity();
}
return $total;
}

And that’s it. Imagine how long it would have required to write a SQL query doing the same thing!

Propel, another open source project, is currently one of the best object/relational abstraction layers for PHP 5. Symfony integrates Propel seamlessly into the framework, so most of the data manipulation described in this book follows the Propel syntax. This book will describe how to use the Propel objects, but for a more complete reference, a visit to the Propel website (http://propel.phpdb.org/trac/) is recommended.

Rapid Application Development (RAD)

Programming web applications has long been a tedious and slow job. Following the usual software engineering life cycles (like the one proposed by the Rational Unified Process, for instance), the development of web applications could not start before a complete set of requirements was written, a lot of Unified Modeling Language (UML) diagrams were drawn, and tons of preliminary documentation were produced. This was due to the general speed of development, to the lack of versatility of programming languages (you had to build, compile, restart, and who knows what else before actually seeing your program run), and most of all, to the fact that clients were quite reasonable and didn’t change their minds constantly.

Today, business moves faster, and clients tend to constantly change their minds in the course of the project development. Of course, they expect the development team to adapt to their needs and modify the structure of an application quickly. Fortunately, the use of scripting languages like Perl and PHP makes it easy to apply other programming strategies, such as rapid application development (RAD) or agile software development.

One of the ideas of these methodologies is to start developing as soon as possible so that the client can review a working prototype and offer additional direction. Then the application gets built in an iterative process, releasing increasingly feature-rich versions in short development cycles.

The consequences for the developer are numerous. A developer doesn’t need to think about the future when implementing a feature. The method used should be as simple and straightforward as possible. This is well illustrated by the maxim of the KISS principle: Keep It Simple, Stupid.

When the requirements evolve or when a feature is added, existing code usually has to be partly rewritten. This process is called refactoring, and happens a lot in the course of a web application development. Code is moved to other places according to its nature. Duplicated portions of code are refactored to a single place, thus applying the Don’t Repeat Yourself (DRY) principle.

And to make sure that the application still runs when it changes constantly, it needs a full set of unit tests that can be automated. If well written, unit tests are a solid way to ensure that nothing is broken by adding or refactoring code. Some development methodologies even stipulate writing tests before coding–that’s called test-driven development (TDD).

There are many other principles and good habits related to agile development. One of the most effective agile development methodologies is called Extreme Programming (abbreviated as XP), and the XP literature will teach you a lot about how to develop an application in a fast and effective way. A good starting place is the XP series books by Kent Beck (Addison-Wesley).

Symfony is the perfect tool for RAD. As a matter of fact, the framework was built by a web agency applying the RAD principle for its own projects. This means that learning to use symfony is not about learning a new language, but more about applying the right reflexes and the best judgment in order to build applications in a more effective way.

The symfony project website proposes a step-by-step tutorial illustrating the development of an application in an agile way. It is called askeet (http://www.symfony-project.org/askeet), and is recommended reading for those who want to learn more about agile development.

YAML

According to the official YAML website (http://www.yaml.org/), YAML is "a straightforward machine parsable data serialization format designed for human readability and interaction with scripting languages." Put another way, YAML is a very simple language used to describe data in an XML-like way but with a much simpler syntax. It is especially useful to describe data that can be translated into arrays and hashes, like this:

$house = array(
‘family’ => array(
‘name’ => ‘Doe’,
‘parents’ => array(’John’, ‘Jane’),
‘children’ => array(’Paul’, ‘Mark’, ‘Simone’)
),
‘address’ => array(
‘number’ => 34,
’street’ => ‘Main Street’,
‘city’ => ‘Nowheretown’,
‘zipcode’ => ‘12345′
)
);

This PHP array can be automatically created by parsing the YAML string:

house:
family:
name: Doe
parents:
- John
- Jane
children:
- Paul
- Mark
- Simone
address:
number: 34
street: Main Street
city: Nowheretown
zipcode: "12345"

In YAML, structure is shown through indentation, sequence items are denoted by a dash, and key/value pairs within a map are separated by a colon. YAML also has a shorthand syntax to describe the same structure with fewer lines, where arrays are explicitly shown with [] and hashes with {}. Therefore, the previous YAML data can be written in a shorter way, as follows:

house:
family: { name: Doe, parents: [John, Jane], children: [Paul, Mark, Simone] }
address: { number: 34, street: Main Street, city: Nowheretown, zipcode: "12345" }

YAML is an acronym for "YAML Ain’t Markup Language" and pronounced "yamel". The format has been around since 2001, and YAML parsers exist for a large variety of languages.

The specifications of the YAML format are available at http://www.yaml.org/.

As you can see, YAML is much faster to write than XML (no more closing tags or explicit quotes), and it is more powerful than .ini files (which don’t support hierarchy). That is why symfony uses YAML as the preferred language to store configuration. You will see a lot of YAML files in this book, but it is so straightforward that you probably don’t need to learn more about it.

For Installation Instruction Please Visit Here.

CakePHP an Open Source PHP Framework

Posted on February 18th, 2008 in Frameworks by Ashish  Tagged , , ,

CakePHP is a free open-source rapid development framework for PHP. Its a structure of libraries, classes and run-time infrastructure for programmers creating web applications originally inspired by the Ruby on Rails framework. Primary goal is to enable developers to work in a structured and rapid manner – without loss of flexibility.

In 2005, Michal Tatarynowicz wrote a minimal version of a Rapid Application Framework in PHP. He found that it was the start of a very good framework. Michal published the framework under the MIT license, dubbing it Cake, and opened it up to a community of developers, who now maintain Cake under the name CakePHP.

Features of CakePHP

CakePHP has several features that make it a great choice as a framework for developing applications swiftly and with the least amount of hassle. Here are a few in no particular order:

1. Active, friendly community
2. Flexible Licensing
3. Compatibility with PHP4 and PHP5
4. Integrated CRUD for database interaction and simplified queries
5. Application Scaffolding
6. Model View Controller (MVC) Architecture
7. Request dispatcher with good looking, custom URLs
8. Built-in Validation
9. Fast and flexible templating (PHP syntax, with helpers)
10. View Helpers for AJAX, Javascript, HTML Forms and more
11. Security, Session, and Request Handling Components
12. Flexible access control lists
13. Data Sanitization
14. Flexible View Caching
15. Works from any web site subdirectory, with little to no Apache configuration involved

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

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 to http://cakeforge.org/projects/cakephp/.

To grab a nightly, download one from http://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

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

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 your app 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’);
}

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.

Database Configuration

Your app/config/database.php file is where your database configuration all takes place. A fresh install doesn’t have a database.php, so you’ll need to make a copy of database.php.default. Once you’ve made a copy and renamed it you’ll see the following:

app/config/database.php

var $default = array(’driver’ => ‘mysql’,
‘connect’ => ‘mysql_connect’,
‘host’ => ‘localhost’,
‘login’ => ‘user’,
‘password’ => ‘password’,
‘database’ => ‘project_name’,
‘prefix’ => ”);

Replace the information provided by default with the database connection information for your application.

One note about the prefix key: the string you enter there will be prepended to any SQL call that Cake makes to your database when working with tables. You define it here once so you don’t have to specify it in other places. It also allows you to follow Cake’s table naming conventions if you’re on a host that only gives you a single database. Note: for HABTM join tables, you only add the prefix once: prefix_apples_bananas, not prefix_apples_prefix_bananas.

CakePHP supports the following database drivers:

1. mysql
2. postgres
3. sqlite
4. pear-drivername (so you might enter pear-mysql, for example)
5. adodb-drivername

The ‘connect’ key in the $default connection allows you to specify whether or not the database connection will be treated as persistent or not. Read the comments in the database.php.default file for help on specifying connection types for your database setup.

Your database tables should also follow the following conventions:

1. Table names used by Cake should consist of English words in plural, like "users", "authors" or "articles". Note that corresponding models have singular names.
2. Your tables must have a primary key named ‘id’.
3. If you plan to relate tables, use foreign keys that look like: ‘article_id’. The table name is singular, followed by an underscore, followed by ‘id’.
4. If you include a ‘created’ and/or ‘modified’ column in your table, Cake will automatically populate the field when appropriate.

You’ll also notice that there is a $test connection setting included in the database.php file. Fill out this configuration (or add other similarly formatted configurations) and use it in your application by placing something like:
var $useDbConfig = ‘test’;

Inside one of your models. You can add any number of additional connection settings in this manner.

Global Configuration

CakePHP’s global configuration can be found in app/config/core.php. While we really dislike configuration files, it just had to be done. There are a few things you can change here, and the notes on each of these settings can be found within the comments of the core.php file.

DEBUG: Set this to different values to help you debug your application as you build it. Specifying this setting to a non-zero value will force Cake to print out the results of pr( ) and debug( ) function calls, and stop flash messages from forwarding automatically. Setting it to 2 or higher will result in SQL statements being printed at the bottom of the page.

Also when in debug mode (where DEBUG is set to 1 or higher), Cake will render certain generated error pages, i.e. "Missing Controller," "Missing Action," etc. In production mode, however (where DEBUG is set to 0), Cake renders the "Not Found" page, which can be overridden in app/views/errors/error404.thtml.

CAKE_SESSION_COOKIE: Change this value to the name of the cookie you’d like to use for user sessions in your Cake app.

CAKE_SECURITY: Change this value to indicate your preferred level of sessions checking. Cake will timeout sessions, generate new session ids, and delete old session files based on the settings you provide here. The possible values are:

1. high: sessions time out after 20 minutes of inactivity, and session id’s are regenerated on each request
2. medium: sessions time out after 200 minutes of inactivity
3. low: sessions time out after 600 minutes of inactivity

CAKE_SESSION_SAVE: Specify how you’d like session data saved. Possible values are:

1. cake: Session data is saved in tmp/ inside your Cake installation
2. php: Session data saved as defined in php.ini
3. database: Session data saved to database connection defined by the ‘default’ key.

Routes Configuration

"Routing" is a pared-down pure-PHP mod_rewrite-alike that can map URLs to controller/action/params and back. It was added to Cake to make pretty URLs more configurable and to divorce us from the mod_rewrite requirement. Using mod_rewrite, however, will make your address bar look much more tidy.

Routes are individual rules that map matching URLs to specific controllers and actions. Routes are configured in the app/config/routes.php file. They are set-up like this:

Route Pattern
<?php
$Route->connect (
‘URL’,
array(’controller’=>’controllername’,
‘action’=>’actionname’, ‘firstparam’)
);
?>

Where:

1. URL is the regular expression Cake URL you wish to map,
2. controllername is the name of the controller you wish to invoke,
3. actionname is the name of the controller’s action you wish to invoke,
4. and firstparam is the value of the first parameter of the action you’ve specified.

Any parameters following firstparam will also be passed as parameters to the controller action.

php.MVC is an open source framework for PHP Web applications

Posted on February 18th, 2008 in Frameworks by Ashish  Tagged , , ,

php.MVC implements the Model-View-Controller (MVC) design pattern, and encourages application design based on the Model 2 paradigm. This design model allows the Web page or other contents (View) to be mostly separated from the internal application code (Controller/Model), making it easier for designers and programmers to focus on their respective areas of expertise.

The framework provides a single entry point Controller. The Controller is responsible for allocating HTTP requests to the appropriate Action handler (Model) based on configuration mappings.

The Model contains the business logic for the application. The Controller then forwards the request to the appropriate View component, which is usually implemented using a combination of HTML with PHP tags in the form of templates. The resulting contents are returned to the client browser, or via another protocol such as SMTP.

php.MVC is a PHP port of Jakarta Struts. It currently supports many features of Struts, including declarative application configuration via the XML digester.

Key Features of php.MVC

• Free OpenSource software: This gives users full control of the software, and the able to modify the source code to suit specific needs.

• Security: php.MVC applications have only one entry point (per application). This makes it easy to protect sensitive application code and data.

• Flexible Installation: Individual php.MVC applications can be installed outside of the main php.MVC library directory tree.

• Multi-applications: There is no limit to the number of applications per php.MVC installation.

• Object Oriented design (OOD). The php.MVC framework is based on OOD principles, making it more extendable and maintainable.

• Database integration: The php.MVC framework ships with the Pear::DB Database Abstraction Layer, and a driver for the MySQL relational database manager (RDBM) is provided.

• Action Chaining: php.MVC allows for passing control to other Actions. This makes it easy to process a sequence of Actions (business logic classes) and static resources (pages).

• XML configuration: php.MVC uses declarative application configurations using Extensible Markup Language (XML) files. Each application has its own XML configuration file.

• MVC Model 2 design: php.MVC implements the Model-View-Controller (MVC) Model 2 design pattern. The Model 2 paradigm allows the separation of the application presentation from the business logic, making it easier for designers and programmers to focus on their respective areas of expertise.

• Form button mapping: php.MVC implements the LookupDispatchAction class to enable HTML form buttons to be mapped to particular business logic methods. For example, a form submit button called "Add to Cart" could be mapped to an Action class method called MyCartAction->addToCart(…).

• Message Resources: php.MVC provides a PropertyMessageResources class that handles messages in text string properties files with parametric replacement. This can provide Locale-sensitive messages for internationalized applications.

• The php.MVC framework is based on Jakarta Struts application framework design. Struts has proven to be reliable, extendable and well supported.

Requirements

• PHP enabled Web server

• PHP v. 4.1.0 or greater

• XML parser (James Clark’s expat is usually included with most PHP versions)

Installation

MS Windows Installation

1) Copy the phpmvc-beta-xxx.zip archive to the Web server (SCP/FTP)

2) Unpack the tarball zip

• SSH to the Web server

• Change to the directory where phpmvc will live. Eg: C:\WWW\

• Backup/move any existing phpmvc directory. Eg: C:\WWW\phpmvc-BAK

• Unzip the phpmvc-beta-xxx.zip archive to the target directory.
Eg: C:\WWW\phpmvc

• Remove the phpmvc-beta-xxx.zip tarball [optional]

3) Setup the Simple Example application

• Move into the main phpmvc directory. Eg: C:\WWW\phpmvc

• Set the Simple Example application root and module directory in Main.php
Note: These paths are absolute file-system paths.
Note: In this case the paths are the same as Simple Example Main.php file is in the php.MVC root directory.

/* ———- Application Paths ———- */
// Set php.MVC library root directory
$appServerRootDir = ‘C:/WWW/phpmvc’; // no trailing slash

// Set the application path
$moduleRootDir = ‘C:/WWW/phpmvc’; // no trailing slash
/* ———- Application Paths ———- */

• Enable write permission on the WEB-INF/phpmvc-config.data file.
Note: The Web server must have write permission on WEB- INF/phpmvc-config.data file
Note: The WEB-INF/* directory tree should be accessable ONLY by localhost per .htaccess file
Note: If you have admin access to the server, change the phpmvc-config.data file to be writable
by the Web server group for added security.

4) Setup the OOHForms demo module

• Move into the OOHForms demo module directory. Eg: C:\WWW\phpmvc\oohforms

• Set the OOHForms demo application root and module directory in Main.php
Note: These paths are absolute file-system paths.

/* ———- Application Paths ———- */
// Set php.MVC library root directory
$appServerRootDir = ‘C:/WWW/phpmvc’; // no trailing slash

// Set the application path
$moduleRootDir = ‘C:/WWW/phpmvc/oohforms’; // no trailing slash
/* ———- Application Paths ———- */

• Enable write permission on the WEB-INF/phpmvc-config.data file for this application.
Note: As above

5) Test Web access to WEB-INF/*

• There should be NO access or directory listing to WEB-INF/* in the main or sub application.

6) Test the basic php.MVC framework demos

• The Simple Example:
Browse to your install directory, with the path "do=stdLogon".
Eg: http://myserver.com/phpmvc/Main.php?do=stdLogon

• The OOHForms demo:
Browse to the phpmvc/oohforms/index.php file and follow the links.

7) Troubleshooting

• If all you get is file path errors, please try setting the $osType variable in the Main.php files to the correct server OS.
Eg: $osType = ‘WINDOWS’;

Linux (Redhat) Installation

1) Copy phpmvc-beta-xxx.tgz to the Web server (FTP)

2) Unpack the tarball

• SSH to the Web server

• Change to the directory where phpmvc will live.
bash$ cd www

• Backup/move any existing phpmvc directory
bash$ mv phpmvc phpmvc-BAK

• Create the phmmvc directory and unpack archive
bash$ tar xvzf phpmvc-20021126.tgz

• Remove the phpmvc-beta-xxx.tgz tarball [optional]
bash$ rm phpmvc-beta-xxx.tgz

3) Setup the Simple Example application

• Move into the main phpmvc directory
bash$ cd phpmvc
Check the path to the phpmvc root directory ($appServerRootDir)
bash$ pwd (/home/myhome/www/phpmvc)

• Set the Simple Example application root and module directory in Main.php
Note: These paths are absolute file-system paths.
Note: In this case the paths are the same as Simple Example Main.php file is in the php.MVC root directory.

/* ———- Application Paths ———- */
// Set php.MVC library root directory
$appServerRootDir = ‘/home/myhome/www/phpmvc’; // no trailing slash

// Set the application path
$moduleRootDir = ‘/home/myhome/www/phpmvc’; // no trailing slash
/* ———- Application Paths ———- */

• Enable write permission on the phpmvc-config.data file.
bash$ chmod o+w WEB-INF/phpmvc-config.data (*** world writable ***)

Note: The Web server must have write permission on WEB- INF/phpmvc-config.data file
Note: The WEB-INF/* directory tree should be accessable ONLY by localhost per .htaccess file
Note: If you have root access to the server, change the phpmvc-config.data file to be writable
by the Web server group for added security.
bash$ chmod g+w WEB-INF/phpmvc-config.data
root# chgrp apachegroup WEB-INF/phpmvc-config.data

4) Setup the OOHForms demo module

• Move into the OOHForms demo module directory
bash$ cd oohforms

• Set the main application root directory in Main.php
bash$ vi Main.php

• Set the OOHForms demo application root and module directory in Main.php

/* ———- Application Paths ———- */
// Set php.MVC library root directory
$appServerRootDir = ‘/home/myhome/www/phpmvc’; // no trailing slash

// Set the application path
$moduleRootDir = ‘/home/myhome/www/phpmvc/oohforms’; // no trailing slash
/* ———- Application Paths ———- */

• Enable write permission on the phpmvc-config.data file
bash$ chmod o+w WEB-INF/phpmvc-config.data (*** world writable ***)
Notes: As above

5) Test Web access to WEB-INF/*

• There should be NO access or directory listing to WEB-INF/* in the main or sub application.

6) Test the basic php.MVC framework demos

• The Simple Example:
Browse to your install directory, with the path "do=stdLogon".
Eg: http://myserver.com/phpmvc/Main.php?do=stdLogon

• The OOHForms demo:
Browse to the phpmvc/oohforms/index.php file and follow the links.

7) Troubleshooting

• If all you get is file path errors, please try setting the $osType variable in the Main.php files to the correct server OS.
Eg: $osType = ‘UNIX’;

User Guides can be found here:

http://www.phpmvc.net/docs/guides/guidesIdx.php

You Can download php.MVC from here

http://www.phpmvc.net/download/downloadIdx.php?doc=phpmvc-docs

 

Buzz about PHP Frameworks

Posted on January 21st, 2008 in Frameworks by Ashish  Tagged , ,

Recently, i have seen a buzz about various frameworks available for PHP. If you have not used a framework and planning to use one, step back, first evaluate your requirements. All frameworks despite being promoted as a rapid application development tool, consider the learning curve that may take place. Learning curve varies for each application framework. If you are doing a one off application, it will be better to do a customize application on your own. You may be able to produce a workable, efficient and lean application faster than when using a framework. If however, your requirement is using this application every in every project that you will be engaging into, then fine, go to frameworks and it will save you development in the long term.

Rasmus Lerdorf (creator of the PHP programming language) is actually against using frameworks in his blog, The-no-framework-PHP-MVC-framework. Rasmus quoted in his blog "…I just happen find most of them too complex for my needs and this is a proposed alternative…". Even Rasmus accepts that fact that frameworks are too complex and argued that the same could be achieved in PHP without using additional external layers. Rasmus provided an example using Yahoo! Application.

Manuel Lemos (PHP Classes) in his blog, Recommended PHP Frameworks (Recommended-PHP-frameworks) provided an advice on what criteria is relevant when choosing a framework that addresses the needs of each PHP developer. He also explained why certain frameworks seem very popular while others are not getting as much attention as their developers hoped. Finally, Manuel Lemos mentioned a long list of packages and tools that make up the framework that is used to implement the PHPClasses site.

Frameworks are always considered as rapid application development tools which make frameworks very appealing at the first instance. However, as Rasmus said in his blog, nobody will build your application for you no matter what the framework promises. Instead you might end up fixing mistakes for the framework instead of spending your time building a lean and reusable pattern that fits your requirements directly.

Here is the list of various PHP Frameworks (All are suitable for particular need but none is viable for all situations)

1. PHP on Trax Strictly follows Ruby on Rails syntax and functionality but written in php5. Originally called PHP on Rails.
2. Agavi an open-source, LGPL licensed MVC framework for creating applications written using PHP5.
3. Akelos PHP Framework a Ruby on Rails port to PHP4/5.
4. BareBonesMVC A one-file, no-configuration, MVC framework for PHP5.
5. CakePHP webapplication framework modeled after the concepts of Ruby on Rails.
6. CodeIgniter A PHP MVC framework.
7. DragonPHP MVC2 Framework for PHP 5.
8. Fusebox Framework for building ColdFusion and PHP web applications.
9. FUSE A powerful but easy-to-use PHP 5 Framework for MVC development
10. KohanaPHP A powerful, lightweight, easily extendable PHP 5 MVC Framework.
11. LightVC Lightweight PHP 5 Strict MVC Framework with decoupling of Model and other non-View-Controller essentials to promote code reuse.
12. Odin Assemble Small footprint PHP based MVC Framework.
13. phpHtmlLib MVC based OO framework compatible with PHP4 and PHP5 licensed under GNU LGPL.
14. phpXCore A MVC design pattern based PHP content management framework compatible with PHP4 and PHP5.
15. PRADO A PHP 5 MVC framework.
16. SilverStripe contains a fully fledged PHP 5.2 ORM/MVC Framework focused on building websites.
17. Solar PHP 5 framework Solar is a PHP 5 framework for rapid application development. It is fully name-spaced and uses enterprise application design patterns, with built-in support for localization and configuration at all levels.
18. OnPHP onPHP is the mature GPL’ed multi-purpose object-oriented PHP framework (plus c-module)
19. Switch board with Routing PHP 5 MVC Framework with Routing.
20. Symfony Framework PHP 5 MVC Framework.
21. TinyMVC Framework Framework Simple and lightweight PHP5 MVC (Model-View-Controller) framework.
22. TYPO3 extension library lib/div PHP 4/5 MVC framework for TYPO3 extension development
23. Qcodo is an open-source PHP 5 web application framework
24. Zend Framework A PHP 5-based MVC framework.
25. ZNF PHP5 MVC framework for enterprise web applications
26.Zoop Framework A Mature PHP 4/5 MVC framework.