We hope you find this tutorial helpful. In addition to guides like this one, we provide simple cloud infrastructure for developers. Learn more →

Getting Started with Phalcon, a PHP Framework - Part 2

Posted Jan 28, 2014 30.5k views PHP Frameworks Ubuntu

About PhalconPHP

Phalcon is a PHP framework that promotes the Model-View-Controller architecture and has many framework-like features you'd expect in a piece of software such as this: ORM, templating engine, routing, caching, etc.

In this tutorial, we will continue where we left off the last time when we got Phalcon installed on our Ubuntu 12.04 VPS and managed to print our first string to the screen using a Phalcon controller. In this tutorial, we will touch upon using the other two core MVC components: the views and the models.

To follow along this article, I assume you have gone through the steps outlined in the previous tutorial and have your Phalcon application printing out Hello World if you point your browser to your ip-address/project-name. So let’s dig in.


In the previous tutorial we created the default Index controller with one method (IndexAction) that does this:
echo "<h1>Hello World!</h1>";

As you know, this is not the best way to print things onto the screen; and like other PHP frameworks out there, Phalcon comes with a templating system that we should use instead. In other words, we can use a View and pass the Hello World string to it through a variable.

The way this works with Phalcon is that in the app/views folder we need to create another folder named as our controller and inside this folder a file named after the controller’s action. This way, Phalcon autoloads this view when the controller action is called. So let’s do this for our first controller/action Index. Create the folder first:
mkdir /var/www/project_name/app/views/index

Inside this folder, create a the file with a phtml extension (named after the controller action):
nano /var/www/project_name/app/views/index/index.phtml

Inside this file, cut the contents of the IndexAction from the controller and paste it in there, between tags:
<?php echo "<h1>Hello World!</h1>"; ?>

Now the controller action is empty, yet the string gets printed from the view that corresponds to that controller/action. So in this short example we have not passed anything to the view yet from the controller, we just demonstrated how the view is loaded automatically. Let’s now declare that variable in our controller, and then pass it to the view to be displayed.

Go back to the IndexController and inside the indexAction method, paste in the following (making sure this is all there is inside this function):
$string = "Hello World!";
$this->view->setVar("string", $string);

In the first line, we set our text value to the $string variable and in the second one we use the setVar method of the view() method of our parent controller class to send this variable to another one that can be accessed inside the view: also called $string.

Now edit the view and replace this:
<?php echo "<h1>Hello World!</h1>"; ?>

With this:
<h1><?php echo $string; ?></h1>

Now you should get the same thing in the browser. Like this, we separated logic (our string value that for all intents and purposes could have been dynamically generated or retrieved) from presentation (the html header tag we wrapped around the string in the View). This is one of the tenets of the MVC architecture and good modern programming practice.

Models and database

Now that we’ve seen controllers and views, let’s connect a database and see how we can interact with it using models. Continuing from here assumes you have already a database you can use, you know its access credentials, and are familiar with basic MySQL commands. If not, check out this tutorial.

To connect our database, we need to edit the bootstrap file we created in the previous article, the index.php file located in the public/ folder:
nano /var/www/project_name/public/index.php

Under this block:
  //Setup a base URI so that all generated URIs include the "tutorial" folder
    $di->set('url', function(){
        $url = new \Phalcon\Mvc\Url();
        return $url;

Add the following block:
  //Setup the database service
    $di->set('db', function(){
        return new \Phalcon\Db\Adapter\Pdo\Mysql(array(
            "host" => "localhost",
            "username" => "root",
            "password" => "password",
            "dbname" => "db-name"

And of course replace where appropriate with your database information. Save the file and exit. Next, create a table that will host your first model. Let’s call it articles and give it an ID column, a title column, and a body column. The following MySQL command will create it for you.
CREATE TABLE `articles` (
  `id` int(10) unsigned NOT NULL AUTO_INCREMENT,
  `title` varchar(255) NOT NULL,
  `body` text NOT NULL,
  PRIMARY KEY (`id`)

Let’s now insert a row through our command line to have something to play with. You can use this MySQL command to do it if you want:
INSERT INTO `articles` (title, body)  VALUES ('This is the first article', 'some article body');

Now that we have some content, let's define our Article model. Create a php file in the app/models folder of your application:
nano /var/www/project_name/app/models/Articles.php

And paste this inside (omit the closing php tag):

class Articles extends \Phalcon\Mvc\Model {


We are now extending the Phalcon model class, which provides a lot of useful functionality for us to interact with our model data. Another cool thing is that since we named the class as we did the database table, the two are already linked. This model will refer to that database table.

Now what we need to do is declare our model properties (that map to the table columns). So inside the class, add the following protected properties:
public $id;

public $title;

public $body;

Next, we need some setters/getters to retrieve from or to assign values to these protected properties. And here we can have a lot to control over how the data can be accessed. But since this tutorial will not look into adding information to the database, we will only add one getter function to retrieve existing information from the property. So below, but still inside the model class, add the following methods:
public function getId()    {
    return $this->id;

public function getTitle()    {
    return $this->title;

public function getBody()    {
    return $this->body;

Normally however, you’ll also need setter functions. Let's save this file and turn back to our IndexController. Inside the IndexAction, replace all the contents with the following:
$article = Articles::findFirst(1);
$this->view->setVar("string", $article->getTitle());

On the first line we use the findFirst method of the Phalcon model class from which we extended our Articles model to retrieve the article with the ID of 1. Then in the second one, we pass to the View the value of the title column that we are retrieving with our getter function we declared in the model earlier. Save the file and reload the browser. You should see printed out the title of the first article.

Since we cannot go into all what you can do with the Phalcon model class, I encourage you to read more about it here. You will find a bunch of ready functionality and database abstraction to get you going fast.


In this tutorial, we've seen how views are automatically loaded by Phalcon given their placement in the project folder structure and also how to pass information from the controller action to its respective view. Additionally, we've set up a small Phalcon model to see how we can interact with a database table and retrieve information.
Article Submitted by: Danny


Creative Commons License