This article is all about building a chat application using Silex; though it is more than just building a chat application. The aim of the article is to familiarize you with Silex. Thus in case you have not come across Silex prior to this, Silex is a PHP micro-framework which has been built for PHP5.3. It has been based on Symfony2 and Pimple and is also inspired by Sintara. It is intuitive and fun to use and has an extension system that is based around the Pimple micro-service container making it easier to tie in third party libraries. Silex uses the Symfony2’s Http Kernel which abstracts request and response. This feature of Silex makes it easier to test apps and the framework itself. Thus while many PHP developers in India are still only getting to know such technology we at Alakmalak are aware of such technology and know how to utilize it for the best of our clients. Alakmalak is a company where web design and web development are taken seriously and done methodically. We are aware about the need to separate the design from the functionality and strive to achieve that by implementing good and proven frameworks where possible.
A micro-framework is like a regular PHP framework stripped to the bare bones. Many of the frameworks are massive and so large that they are hard to handle. That may be overlooked if your project is a large one and uses many different features that would be usually found in such a big framework. On the other hand if you really only need to build a small applications in PHP and want to use a framework it is kind of unnecessary to carry excess baggage so to speak. Hence micro-framework is the striped down version of a regular framework that can get all the things done and in a nice manner without the extra features that you generally don’t require in a small application. Micro-frameworks encourage swift development and can be incredibly useful when a quick site is needed. There are several popular micro-frameworks around. Silex is one such micro-framework that is strongly built upon the powerful Symfony components.
Implementing a template goes a long way in helping separate our concerns, so that the designers and the developers can work with the dynamic web pages in a more maintainable way. For those who have considerable experience either a designer or a developer they must have come across web pages during their career that mixes both the HTML code meant for the layout of the site with PHP code that is meant for the functionality of the website. This is perfectly fine if it is a very small application or piece of code. But the second we try to build a decent application where slightly complicated procedures are involved along with complicated designs this kind of practice can make the code quite messy and hard to maintain, if not impossible. Thus comes the template engine to the rescue. The template engine is a piece of software that takes the template files and renders them as HTML. A template file is similar to HTML and PHP files except that the PHP syntax has been replaced with a template language syntax. The advantage being that since it is set use along with HTML it looks much cleaner and can even be helpful in rendering dates. The template language that will be used along with Silex is Twig due to its easy integration with Silex.
Twig is a modern template engine for PHP which compiles templates down to plain optimized PHP code. It is highly secure and gives the users the ability to create their own custom tags and filters.
Silex Project Structure:
Alternatively you can also download Composer-Setup.exe for windows from https://getcomposer.org/Composer-Setup.exe and simply follow the installation instructions. Composer is a dependency manager. Composer is a smart tool that seeks the dependencies in your project and then downloads them into your project. For example you have a project that depends on a number of libraries and that in turn depends on many other libraries. You can go ahead and declare the things you depend on and Composer will find which versions of which packages need to be installed and then download them into your project.
We first need to create a file called composer.json in the root of the project that tells the Composer which dependencies we want to install. Then open the command line at the root of your project and run composer file by typing a command line. Running this command with the suitable options will download your dependencies and place them into a /vendor/ directory.
We now need to make an index.php file in the /src/public/ directory. This will be the file we point our browsers at. It simply requires another index.php file from the /src/private/ directory. This is simply to a security precaution so that the internal sensitive data is remains hidden.
Code for the index.php file (/src/public/):
It is time to check our Silex installation to check if it is working correctly. We can do this by simply printing ‘Hello World!’ on the page when someone visits the homepage. To do this we need to define a route. A route tells our server to perform an action when a URL is requested. We can define a route by calling the get() method on the $app object (since we want to define a route for a GET request). The get() method takes two arguments; the route represented as a string ( in this case ‘/’) and an anonymous function defining the action to take upon handling the request, which is our ‘Controller’.
use Symfony\Component\HttpKernel\Httpkernel Interface;
$app = new Silex\Application();
$app[‘app.url’] = ‘http://localhost:8080’;
$app[‘app.path’] = ‘/src/public/index.php’;
$app[‘app.assets’] = ‘/src/public/assets’;
$app[‘elephant.address’] = ‘http://localhost:4568’;
$app[‘twig.templates.dir’] = __DIR__ . ‘/../private/templates’;
$app->register(new Twig ServiceProvider(), array(‘twig.path’=>$app[‘twig.templates.dir’],));
$app->register(new ElephantIOServiceProvider(), array(‘elephant.address’ => $app[‘elephant.address’]));
$app->get(‘/’, function() use($app)
return “Hello World!”;
Here we have made use of anonymous functions which were introduced in PHP 5.3 which are function that have no name. Instead they may be defined as arguments. As per the above code we have simply returned the string ‘’Hello World!’. Thus when we visit it in our browser it should handle the request correctly.
We can extend the functionality of Silex by using service providers. We will be needing Twig (for the template engine) and ElephantIO (to communicate via socket.IO in PHP). We can register a new service provider by calling register() on the application object. The register() method takes two arguments, a service provider and an array of parameters.
We first register the Twig service provider with the parameters including the path to the template directory. (this tells Twig where to look for its templates files). The next thing we do is register the Elephant Io service provider.
We can now modify the root controller to return a Twig template instead of just the text ‘Hello World!’. We are calling the render method of Twig and returning the output. We pass the render function the name of the template we want to display and an array of variables we like to inject into the template. We also need to handle the POST requests from our application. We can do this by setting up a route in Silex. In our post request controller we get the details of the message from the request, then send that message to Socket.IO.
$app->get(‘/’, function() use($app)
return $app[‘twig’]->render(‘home.twig.html’,array(‘url’ => $app[‘app.url’], ‘assets’ => $app[‘app.assets’], ‘socket_address’ => $app[‘elephant.address’], ‘app_path’ => $app[‘app.path’]
$app->post(‘/’, function() use($app)
$message = array(‘message’ => $app[‘request’]->get(‘message’), ‘user’ => $app[‘request’]->get(‘user’));
$app[‘elephant’]->emit(‘’new_message’, $message, null, null);
return $app->json(‘Success!’, 200);
That covers most of our backend building though we are yet to do the template.
Template Engine With Twig:
We now need to install Node.js to power our web apps. The installation instructions are available at their website (http://nodejs.org). Once that is installed we need to use NPM (Node packet manager) to add the socket.IO package to node. Make a new file in /src/server called server.js.
That just about sums it up, you can go to the index.php file in the browser and it will load a form which you can use to send messages online.
We often have the need to build one page applications and end up using full-fledged frameworks to do the job. There is an alternative to using an entire framework like Symfony2 or any other for that matter. The alternative is micro-frameworks that utilize development tools. This not only makes the coding small easier but also makes it more rapid. Silex is one such micro-framework that can utilize several development tools like node.js, composer and several others to build a single page app real quick.
Feel free to contact our web development team today.
If you like this blog Please Plus it, Like It ,Tweet It and best yet link to It.