Tutorial

How To Use Lithium to Create a Web App

Published on February 6, 2014
How To Use Lithium to Create a Web App

Status: Deprecated

This article covers a version of Ubuntu that is no longer supported. If you are currently operate a server running Ubuntu 12.04, we highly recommend upgrading or migrating to a supported version of Ubuntu:

Reason: Ubuntu 12.04 reached end of life (EOL) on April 28, 2017 and no longer receives security patches or updates. This guide is no longer maintained.

See Instead: This guide might still be useful as a reference, but may not work on other Ubuntu releases. If available, we strongly recommend using a guide written for the version of Ubuntu you are using. You can use the search functionality at the top of the page to find a more recent version.

About Lithium


Lithium is a full stack PHP framework for developing web applications. Based on the Model-View-Controller (MVC) architecture, it is built for PHP 5.3+ and integrates with the latest storage technologies like MongoDB or CouchDB.

It is designed to offer both a great project organisation as well as the possibility to code out of the framework as you develop your own unique web application. Additionally, it features a robust plugin system that allows you to use your favorite components from outside the framework (such as Twig for templating or Doctrine2 for ORM).

In this tutorial, we will continue where we left off previously when we installed Lithium onto our Ubuntu 12.04 VPS and configured all the necessary requirements for building our web application. If you remember, we also connected a MySQL database and had a glimpse of how to print out “Hello World” onto the page. What will follow now is illustrating how to use the three MVC components (Models, Views and Controllers) together with the Lithium framework.

Controller


We’ve seen already in action a simple controller class (HelloController) and its index (that is, its default) method. We’ll continue building on it to illustrate 3 more MVC related aspects:

  • Using other controller class methods and how they related to the URL that we call in the browser

  • Passing information from the controller to be displayed in a View (which is a best practice as opposed to just echo-ing strings directly from the controller methods).

  • Creating a model to represent our data in the database

Routing


To illustrate how the controller maps to the URL we need to access in the browser, let’s create another method in our HelloController:

public function goodbye() {
    echo "Goodbye!";
}

Now when we point our browser to your-ip/sites/hello/goodbye, we’ll see the word “Goodbye” printed on the screen. This is the defaul routing behaviour of Lithium by which the first url parameter that we pass is the name of the controller (Hello <- notice the lack of the word “Controller”) and the second one is the name of the method (goodbye).

We can take if further and even pass a parameter to the method like so:

public function goodbye($name) {
    echo "Goodbye " . $name . '!';
}

Then we can point our browser to your-ip/sites/hello/goodbye/danny and you’ll see printed “Goodbye danny!” on the screen. So it’s quite handy and logical, working similar to CodeIgniter.

As straightforward as this may be, it does not satisfy the need of every project. In that case, you have the possibility to define custom routing rules and map urls to controller methods as you want. Read more information on the Lithium documentation site.

Views


As I mentioned, the MVC architecture promotes a separation of logic from presentation so let’s see how we can use Lithium Views to display information built in our HelloController class. Going back to the goodbye() method we created earlier, let’s assume that we need the parameter we pass to it (the $name) printed out in a View.

The first thing we need to do is have this method pass the variable to the View. One of the ways this can be achieved is by returning an associative array of keys and values. Therefore, alter the goodbye() method to look like this:

public function goodbye($name) {
    return array(
      'name' => $name,  
    );
}

As you can see, all the method does is returns an array that contains the variable (passed from the URL). The key that correlates with the $name variable will be available in the View for outputting as a variable.

Now, let’s go ahead and create a View file in the app/views/ folder that has the same name as the controller method, and resides in a folder named after the controller. So in our case it would be (while being in the project root folder):

nano app/views/hello/goodbye.html.php

Inside this file now paste the following:

<h1>Goodbye <?=$name;?>!</h1>

Now when you navigate to the previous url:

your-ip/sites/hello/goodbye/danny

You should see in between the header tags how the $name variable we got from passing to the controller, in turn was passed to and printed by the View. Another cool thing is that the value gets escaped automatically by Lithium.

You’ll also notice that our view is injected inside an existing layout that comes by default with Lithium (with a small menu at the top etc). But for more information about using Views and layouts, check the Lithium docs.

Models


Having seen how we route requests and display information, let’s see how we can get information from our database by creating a model to represent it. And since convention goes a long way with Lithium, we won’t have to do a lot before we can see some awesome results.

First off, make sure you have the database and a table in it. I will call mine news and it will have 3 columns: id, title, and body. Additonally, populate this table with some dummy content so you have something to play around with. For more information about working with MySQL, you can read this great tutorial on DigitalOcean. But don’t forget that with Lithium you have the option of using other storage engines.

To speed things along you can quickly create this table from the command line after logging in to your MySQL server by running this command:

CREATE TABLE `news` (
  `id` int(10) unsigned NOT NULL AUTO_INCREMENT,
  `title` varchar(255) NOT NULL,
  `body` text NOT NULL,
  PRIMARY KEY (`id`)
);

And you can also insert two dummy rows with the following two commands:

INSERT INTO `news` (title, body)  VALUES ('This is the first news article', 'some article body');
INSERT INTO `news` (title, body)  VALUES ('This is other news', 'some more article body');

Now that we have some content, let’s create a News.php file to hold our model class in the app/models/ folder:

nano app/models/News.php

Inside, paste the following:

<?php

namespace app\models;

class News extends \lithium\data\Model {
}

?>

For now, that’s all we need in this file. The base class we are extending provides plenty of methods we can use to interact with our data.

Back in our HelloController class, add the following line above the class declaration:

use app\models\News;

Now let’s add another method inside the class:

public function news($id) {
    $news = News::first(array(
      'conditions' => array('id' => $id)
    ));
    return array(
      'news' => $news->data()  
    );
  }

This method takes the parameter from the URL (the news id), retrieves the news with that id, and passes the result to the View. It uses the Lithium Model base class to do the query using the find() method, and the data is then accessed in the resulting object using the data() method. Now let’s create the View to show the news article:

nano app/views/hello/news.html.php

And paste the following:

<h1><?=$news['title'];?></h1>
<p><?=$news['body'];?></p>

When making these changes, be sure that you have the correct MySQL credentials in the configuration file:

nano /var/www/site/app/config/bootstrap/connections.php

As you can see, the $news variable is an array with keys named after the table columns. Neat. Now point your browser to the following url:

your-ip/site/hello/news/1

And you should see the first news article. Pass 2 as the last argument and you should see the second news article, etc. For more detailed information about using Lithium models, read the respective docs here.

Conclusion


In this tutorial,we’ve played around a bit with Lithium, learning how the basic routing system works and how the URL gets translated into controller requests. Additionally, we’ve seen how to work with Views to show information passed from controllers and how to integrate our database information using models.

<div class=“author”>Article Submitted by: <a href=“http://www.webomelette.com/”>Danny</a></div>

Thanks for learning with the DigitalOcean Community. Check out our offerings for compute, storage, networking, and managed databases.

Learn more about us


About the authors

Still looking for an answer?

Ask a questionSearch for more help

Was this helpful?
 
1 Comments


This textbox defaults to using Markdown to format your answer.

You can type !ref in this text area to quickly search our full set of tutorials, documentation & marketplace offerings and insert the link!

Thanks for this!

Try DigitalOcean for free

Click below to sign up and get $200 of credit to try our products over 60 days!

Sign up

Join the Tech Talk
Success! Thank you! Please check your email for further details.

Please complete your information!

Get our biweekly newsletter

Sign up for Infrastructure as a Newsletter.

Hollie's Hub for Good

Working on improving health and education, reducing inequality, and spurring economic growth? We'd like to help.

Become a contributor

Get paid to write technical tutorials and select a tech-focused charity to receive a matching donation.

Welcome to the developer cloud

DigitalOcean makes it simple to launch in the cloud and scale up as you grow — whether you're running one virtual machine or ten thousand.

Learn more
DigitalOcean Cloud Control Panel