Lithium Framework 1 – Basics

Lithium Framework is a PHP 5.3.x Compatible MVC Framework. Like Most PHP Frameworks it takes a bit to get used to, however I have found that this one is very easy to understand and to modify. I am not going to lie, like most Open Source projects the documentation on this framework blows hard-core. That is partially why I am writing this article. This article is meant as a how-to guide. With that said lets start.

The first thing you will want to do once you have uploaded and configured your instance of lithium will be to change the apache web root to be /app/webroot/. This is mainly for security and URL friendliness sake. You will need to have mod-rewrite turned on in apache. But since this is 2011 I hope all web servers have that by now.

So the basics.
Routes Routes Routes. No I am not talking about A ot B stuff…but mainly how the framework parses requests and dispatches those requests to controllers.

The route configuration is located in \app\config\routes.php
I have setup several static routes. Lets take a closer look at them.

So you will see that the very first route I define is:

Router::connect(‘/’, ‘Pages::view’);

Basically what this route says, is that when going to the page with no controller specified route the request to the Pages Controller and the View of that controller. Basically when going to www.xyz.com/ it will show the Page/View. Simillary we see that there are other static routes:

Router::connect(‘/login’, ‘Pages::login’);
Router::connect(‘/join’, ‘Pages::join’);
Router::connect(‘/tos’, ‘Pages::tos’);
Router::connect(‘/forgot’, ‘Pages::forgot’);
Router::connect(‘/reset’, ‘Pages::reset’);
Router::connect(‘/irc’, ‘Pages::irc’);

These where just for URL friendly stuffs. Who wants to see xyz.com/pages/login ?

Next up is the Parsing Magic.

Router::connect(‘/{:controller}/{:action}/{:args}’);

This allows the system to tkae the URL as a parameter and dispatch accordingly.
Example: URL: xyz.com/admin/home will dispatch to the Admin Controller’s home function. Pretty simple Right? I thought so.

So like everything good, lithium has a wonderful directory structure.
Controllers are located in \app\controllers\
Models are located in \a[[\models\
Views are located in \app\views\

In the attache files you will see examples of all of them. So How does it all work?

Well lets go through a specific Example.

Browsing to xyz.com/

The system takes the / as a paramter.
The system then Dispatched the request to the Pages controller and then calls the view function.

Here is the Pages::view()

    public function view() {
$this->_render['template'] = “home”;
}

What is this? Well this line tells the system to use the home template in the Views Pages folder. Typically and Im pretty bad for this…Every Function should have a corresponding HTML template page in the Views folder. However you can redirect the system by changing the template name. In this case instead of a view.html.php file there will be a home.html.php file. The system then renders the template file and vola. you have your page.

Pretty easy eh?

Next we will talk about how data is handled in Lithium.

Attached Files:

lithium-0.0.1

Tips n Tricks 3 – PHP Active Record and Autoloading Forms

So in this article I will show some sample code taken from one of my projects that shows an easy way to modify records with any data-set size.

So what we want to do is place this code in our php page and include the needed jquery libs and what not. for the ID we will get this via $_GET. So the page URL would be, http://example.com/user/edit/?id=4

jQuery:

$.get(
“http://example.com/user/to_json/”,
“id=<? echo $_GET['id']; ?>”,
function (p) {
for (var key in p) {
if (p.hasOwnProperty(key)) {
$(“#”+key).val(p[key]);
}
}
}, “JSON”);

PHP

<?php

use \app\models\User;

 

//…Controller Definition

 

public function edit() {
$data = $_POST;

if (isset($data['submit'])) { //was the page submitted
unset($data['submit']); //remove the submit button…dont need to save that in the DB.
$user = NULL; //for scoping
if ($data['id'] == 0) { //new record?
$user = new User($data); //create record, but it doesnt save it
}
else {
$user = User::find($data['id']); //find and load old record
$user->update_attributes($data); //update record
}
$user->save(); //save changes to database
}

}

 

public function to_json() {

$data = $_GET;

$user = User::find($data['id']);

echo $user->to_json();

die();

}

 

//..End Controller

?>

So this code is taken from one of my User Controllers. See MVC Frameworks for more information on Controllers. But basically what the framework does is take everything AFTER the .com/ in the URL and breaks it into parts.

http://example.com/<controller>/<view>/

The framework then calls the Controllers’ View function to load a page. So in the instance of the edit page, it calls the Edit function and same with the to_json. The jQuery loads the to_json page which is a json outputted user object. Of course I leave the form variables to you.

But basically if you have the same name for a data-column in the database as the form element. This code auto-reloads and saves the data, which is a huge time-saver when doing large forms. It allows for rapid prototyping and easily saves HOURSSSSSS over work.

Tips n Tricks 2 – PHP Active Record

This article explains the awesomeness of PHP Active Record. Basically Active record is a design pattern that allows developers to abstract the hard-core sql queries and escaping those queries into a library. PHP Active Record requires PHP 5.3.x. For more information on it visit their website. www.phpactiverecord.org/

How to update a Record. Data is passed via $_POST;

<?php

use \app\models\User;
$data = $_POST;

if (isset($data['submit'])) { //was the page submitted
unset($data['submit']); //remove the submit button…dont need to save that in the DB.
$user = NULL; //for scoping
if ($data['id'] == 0) { //new record?
$user = new User($data); //create record, but it doesnt save it
}
else {
$user = User::find($data['id']); //find and load old record
$user->update_attributes($data); //update record
}
$user->save(); //save changes to database
}

?>

Of course there is a bit of work to get active record installed and configured…but as you can see it is well worth it. Active record also has handy functions like, ->to_json(). See T&T part 1 ;) and Ill put it all together in part 3.

Tips n Tricks 1 – Auto loading a form

This article will show you a neat way to use jQuery’s AJAX framework to auto-populate a form.

jQuery Code:

        $.get(
“URL”,
“id=ID”,
function (p) {
for (var key in p) {
if (p.hasOwnProperty(key)) {
$(“#”+key).val(p[key]);
}
}
}, “JSON”);

So what do we see here? Well the Script grabs a JSON object (Basically your form data) and iterates over each property. The trick here is that your form elements have to be the name as the properties so they get mapped correctly.

You should see the PHP Active Record Plugin for how to put your form data into a database without the need of writing pesky insert statements.

 

MySQL Introduction

So you want to learn about databases huh?

Well this article will cover off the most basics of basics. Here is the table of contents for our first peak at database management.

  1. Create Database
  2. Create Table
  3. Insert Data
  4. Update Data
  5. Delete Data
  6. Query Data

The goal is at end of this article that you have a basic understanding of how to preform all of these functions inside a database.

I recommend that you use the SQLYOG Tool to interface with your database.
You can get the community version here. http://code.google.com/p/sqlyog/

So lets talk about Databases now.
A database is really just a set of objects. It is best practice to make sure that a database only contains stuff that is in some-way related to each other. For example: You do not want your Blog database merged with say. your accounting database. The reasons should be clear however I should probably go over the “rules” of database design in the Real World.

  1. Keep data sets separate. This is for security and for maintainability sake. Think of it as organizing stacks of paper. You want distinct piles of paperwork otherwise you will never know where anything is.
  2. Never have redundant fields. We will discuss this later on in a design article.
  3. Use proper-naming when appropriate.

Most of this is common sense. So now that we have some ground rules lets dive into actually doing some cool stuff.

1. CREATE DATABASE – http://dev.mysql.com/doc/refman/5.0/en/create-database.html

So lets look at the most basic syntax of the statement.

CREATE DATABASE <name>;

Pretty simple yes? I thought so.
So lets go ahead and create our first database.

Create Database Blog;

Yay, Our First database.
That was cool? No…I guess it wasn’t. All we did was create a virtual “pile”. There’s nothing in it…Yet.

2. Create Table - http://dev.mysql.com/doc/refman/5.1/en/create-table.html

Well now we are getting somewhere. This command will allow us to create a object or rather in database geek speak, a Table. Tables hold data or you can think of it as a document in your pile.

Before we get into the syntax of creating our very first table we will need to outline some specifics about data-columns.

The first and most important thing is something called a Primary Key. The primary key is a data-column dedicated to making sure each data-row is unique. The standard name for this column is “id” and it represents a integer auto-generated by the database. Every time a new data-row is created a new id gets created as well. An example of this might be something like, Employee #. The Employee # is unique to a single individual and thus would be considered a Primary Key. For the most part every data table should have a Primary Key. Just like everything there are exceptions to this rule which we will discuss at a later time.

So lets take a look at a Create Table Command.

CREATE TABLE `Blog`.`Posts` (
`id` INT NOT NULL AUTO_INCREMENT,
`name` VARCHAR (255),
`post_text` TEXT,
PRIMARY KEY (`id`)
) ;

So lets break this down. The first line tells the database what the table name is going to be. The () tells the database about the contents of the table. Next comes the data-columns. They are always represented in this fashion:

`<name>` <type> <NULL | NOT NULL> <OPTIONS>

We see in this case the first column is the special Primary key field. The primary key should always have the AUTO_INCREMENT attached. This lets the system auto-generate a positive non-zero unique #. The primary key should always be of INT as well. We will discuss data types later on in another article.

The next 2 lines define 2 more data columns, 1 of a String with max length of 255, The next of Text. Text fields are strings as well, however their max length is much larger than 255. The final line tells the database that the primary key is the column named id.

There we go our first data-table! Next up how do we use it!

3. MySQL INSERT -

Inserting data is very easy.

INSERT INTO `Blog`.`Posts` (`name`, `post_data`) VALUES(‘abcde’, ’123456′);

The first set of () defines the order and what data fields you are putting data into. Note that ID has no data being inserted. That is handled by the system. It is possible to leave out data columns when inserting data, only define columns you have data for, never insert blank data into a column.

The VALUES() defines what data is going in. It is processed in the same order as the columns defined previously. So the database will set name = abcde, and post_data = 123456.

4. Updating Data -

Well thats fine and dandy but how do I update it if I make an mistake. Well its just as easy.

Update `Blog`.`Posts` set `name` = ‘abcde’, `post_text` = ’123456′ WHERE id = 1;

So as you can guess we are switching the values around in our Post. We are also seeing a new clause, the WHERE clause. The where clause is used as a filter when using an UPDATE or SELECT statement. Obviously when updating we generally only want to affect 1 record. This is where the ID column comes in. Since it was our first post, it’s id number should be 1. Want to affect every post? just drop the where clause.

Where clauses can also use greater and less than. Not Equal is defined by <>. But we will get into more detail about this later.

5. Delete Data

So well that’s all nice, but I really just want to get rid of that post now.

DELETE FROM `Blog`.`Posts` WHERE id = ’1′;

…Bam! Post gone.

6. Query Data

Well what if i want to find posts. Well my friend that is handled via the SELECT statement. The select statement is the bread-and-butter of databases. It is how you retrieve your information.

SELECT name, post_data FROM `Blog`.`Posts`;

This query will do what?
If you said return all data-rows of the Posts table you are correct!

Want to get the latest 5 posts?

SELECT name, post_data FROM `Blog`.`Posts` Order By id desc LIMIT 5;

Here we introduce the Order By Clause and the LIMIT clause. I think they are pretty self-explanatory. Order tells the database in which order you want the data, and LIMIT says how many items you want.

Well maybe you want the most recent 10 posts pertaining to Obama.

SELECT name, post_data FROM `Blog`.`Posts` WHERE post_data LIKE ‘%Obama%’ Order By id desc LIMIT 10;

What is all this? LIKE? Well its exactly what it looks like. Like returns all items that match its Expression. In this case it is anything that contains the word Obama. Notice How i said contains. That means that Obamainator is a valid match. If you just wanted Obama, omit hte %s. %s is a wild-card, meaning any text.

Anyway this is the end of the first Tutorial.
I hope you enjoyed it.