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.
Make Chat Application – Silex Using PHP
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 Symphony 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:
The /public/ directory will contain the publically accessible elements of our project. All the imported code will be placed separately from our own code. The /vendor/ directory will store all our dependencies.
Directory Structure Of Our Project – Silex Using PHP
We shall now be using a component dependency tool. The composer website provides instruction on how to quickly install it via the command line. It is possible to download composer.phar from Packagist (https://packagist.org). You can then follow the instructions and install it.
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.
Building the index – Silex Using PHP
Building The Index:
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:
When our app received any incoming message, it will insert it into this discussion box. We will also include a message form div, which will enable the user to post a message. This HTML form utilizes jQuery to perform a request in the background, so we don’t need to reload the page.
We need to listen for incoming messages so we are going to connect to Socket.IO directly. We then call the on() method of the socket object to tell it to listen for the new_message event and run the passed function when that event occurs. The function we are passing will be responsible for appending the incoming message to the discussion box.
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.
Node Packet Manager – Silex Using PHP
This is our node.js server which is going to accept incoming messages and broadcast them to any clients listening. The code is really quite simple. We are requiring the Socket.IO package first from Node, telling it to listen to port 4568 and then assigning it to a variable. We then tell Socket.IO to call a function when the connection event occurs.
We can then say that we have set up a listener on the connection event. We actually go on to use our connection listener to wire up another event when a client connects. We call a function when the new_message is
node.js server – Silex Using PHP
fired. That function uses the emit() function to pass data received by the new_message event to any listening clients.
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.
Quick Chat Application – Silex Using PHP
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.
Why Choose Alakmalak As a Your Growth Partner?
Alakmalak is a web development company in India that offers services for several technologies. There have been around for a very long time and have developed over 2500 projects for clients all around the world. They have highly skilled web developers with a great deal of experience.
- Build a Chat Application With Silex Using PHP
- Creating new service providers in Silex in Php