Getting Started with Silex Micro-Framework on Cloud Hosting

by Shahroze Nawaz  September 7, 2016

Extensibility is one of the main aims of web app development projects. However, there are times when you need to get things up and running as soon as possible and with minimum time dedicated to coding. This is where micro-framework s really outshine the competition. There is a long list of these frameworks including Silex, Slim, Lumen, etc. These are ideal for developing small-scale applications with clean code and user defined directory structures.

How to install silex on cloud hosting

In this tutorial I am going to explain how to install Silex on cloud hosting servers, its operation, directory structure, Routings and HTTP Requests. Silex is a micro-framework written in Symfony and inspired by Sinatra, a DSL for quickly creating web applications in Ruby with minimal effort.

How to Install Silex on Cloud Hosting

To install Silex on Cloudways cloud hosting platform, you first need to create an account and then launch a new server with a PHPStack application.

php server cloudways

After launching the application, open SSH Terminal by clicking Launch SSH Terminal.

launch ssh terminal on cloudways

Now login to SSH by using the Master Credentials as shown above. After logging in, go to the application folder through the following command

Since Composer comes pre-installed on Cloudways, installation of Silex is the matter of running the following command:

If you do not wish to install it from Composer,  You can clone it from GitHub

You also need to install a templating engine. Since Silex is based on Symfony, it works very well with Twig, the default templating engine of Symfony. To install Twig, just run the following command.

Silex 2.0 is now successfully installed on the cloud server. Let’s now check out the directory structure and how to add user created directories.

Directory Structure

Directory structure plays a significant role in application development. Models, Controllers and View files are stored in specific folders. Silex allows user created directory structure. When you install the framework, you just have a vendor folder in the app. You have to create more folders like Views to store template file, Models to store entity files, and Public to store homepage and other CSS files.

Following is the recommended directory structure that you should create:

You are pretty much free to name the folders anything. However, the good practice is to follow the Symfony directory structure to keep things familiar and understandable.

The application that I will create shortly runs from the public folder using the index.php. This is why I am going to initialize the Silex application in index.php.

First I need to require the dependencies by

Now initialize Silex in it

You can also test whether Silex has been initialized through a simple var_dum($app). It will return the object on screen if everything is working correctly!

Now to check errors and exceptions, I will also initialize a debug environment. Simply add the following code

After finishing the application code, add this line to execute the app in the browser.

At this point, you are probably comparing Silex and Slim. Both are excellent micro-framework s. However, as you shall see, Silex often proves to be a better choice for your projects!

Routing

If you are familiar with Slim or Express, you are very much familiar with how routing techniques are used in micro-framework s. In Silex, you define a routing path and a controller with it which is called when the route path matches. For instance, Silex route contains two parts pattern (Routing path) and method(HTTP Request)

Let’s say, there is an array containing information about books

Now, if you browse this application’s URL and add the suffix /library, you will get the books’ titles as output.

Silex also allows dynamic routing so you can get single results by providing parameters in route and define a variable in the method for this.

If you noticed, I have used abort() here which will throw a 404 message if the id does not exist.
Now let’ check out an example for POST route. To create a resource, you need to add Request and Response Dependency in index.php file

Now you can make a request like this

In this simple example, I created a request to create an email message and send it to the recipient. It also shows that the email was sent after 200 responses. Silex has a swiftmailer bundle, eliminating the need to use mail method.

You can use several HTTP Requests like PUT,DELETE,PATCH,OPTIONS to interact with resources. For example,

Match

Silex has a unique routing Request called match. Basically, it will match all the routes and if any route matches, the response will be sent. We can also restrict it with method();

Convert

Normally, you get values from the requested URL and save them in a variable to pass on to the Controller. Silex provides the convert method to apply conversions before passing on the variable’s value to Controller.

We can also use regular expression to make sure that the returning data type is correct using assert().

You might be interested in: How to Create Simple Rest API in Symfony 3.1

Controllers as Classes

Controllers as classes is a unique feature of Silex. In actual practice, an anonymous method is assigned to each route. However, you can also assign controllers as methods directly by using ControllerClass::methodName syntax.

Suppose, you have a controller with the name HomeController in Myapp/Controllers. You can define it as.

After this, You can create  an object for this controller

This will load the MyApp\Controller\HomeController class on demand, create an instance and call the newfunction method to get the response. You can use Request and Silex\Application type hints to get $request and $app injected.

Providers

Silex needs some dependency to work with bundles like twig, swiftmailer etc. Of course, you can install them by using Composer. If you need to use these bundles in the application, you need to register it in the code. For instance, if you need to use Twig,

This will load the template files to render them like this,

Middlewares

Similar to Express, Silex also allows to define middlewares in routes. Middleware can be used to carry out some actions before the Controller is executed. Silex provides two types of Middlewares.

Application:

This middleware runs independently for the current request. Routing request can be defined as,

Route Middleware:

This middleware runs when the specific route is matched. While similar to Application Middlewares, they are called right after the matching route

Conclusion

Silex is an ideal framework for rapid app development. Since I did not cover everything in this article, but you can gear up with the information to a better understanding of the framework. Silex is based on Symfony and inherits Symfony’s architecture and efficiencies. To make sure everything works, it is important to understand how to correctly install the framework on reliable Silex cloud hosting. You can also go through the official documentation for a more indepth understanding of how the framework operates.

If you have any queries, please leave a comment below.

Create PHP websites without the worry of server management.

Deploy your PHP app on optimized PHP hosting servers.

About Shahroze Nawaz

Shahroze is a PHP Community Manager at Cloudways - A Managed PHP Hosting Platform. He’s always in search of new frameworks and methods to implement them. Besides his coding life, he loves movies and playing soccer with friends. You can email him at shahroze.nawaz@cloudways.com

Stay Connected:

You Might Also Like...