Chat with us, powered by LiveChat

This website uses cookies

Our website, platform and/or any sub domains use cookies to understand how you use our services, and to improve both your experience and our marketing relevance.

Getting Started with Silex Micro-Framework on Cloud Hosting

September 7, 2016

6 Min Read
Reading Time: 6 minutes

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 on Cloudways PHP MySQL hosting, 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

cd application/{your_app_folder}/public_html

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

composer require silex/silex “2.0”

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.

composer require “twig/twig:~1.0”

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:

|-app/
|----config/
|-resources/
|----views/
|----logs/
|-src/
|----MyApp/
|-public/
|----index.php
|----.htaccess
|-vendor/
|-composer.json

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

require_once __DIR__ . ‘/../vendor/autoload.php’;

Now initialize Silex in it

$app = new Silex\Application;

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

$app[‘debug’] = true;

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

$app->run()

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

$books = array(

1 => array(

'ISBN' => ‘BK-2456’',

'author' => 'Sensiolabs',

'title' => 'How to start with silex',

),

2 => array(

'ISBN' => ‘BK-2986’',

'author' => 'Michael',

'title' => 'Getting started with silex',

),
);

$app->get('/library', function () use ($books) {

$output = null ;

foreach ($books as $post) {

$output .= $post['title'];

$output .= '<br />';

}

return $output;

});

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.

$app->get('/library/{id}', function (Silex\Application $app, $id) use ($books) {

if (!isset($books[$id])) {

$app->abort(404, "Post $id does not exist.");

}

$post = $books[$id];

return "<h1>{$post['title']}</h1>".

"<p>{$post['author']}</p>";

});

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

use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;

Now you can make a request like this

$app->post('/feedback', function (Request $request) {
$message = $request->get('message');
mail('feedback@yoursite.com', '[YourSite] Feedback', $message);
return new Response('Thank you for your feedback!', 201);
});

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,

$app->put('/library/{id}', function ($id) {
// ...
});
$app->delete('/library/{id}', function ($id) {
// ...
});
$app->patch('/library/{id}', function ($id) {
// ...
});

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();

$app->match('/blog', function () {
// ...
});
$app->match('/blog', function () {
// ...
})
->method('PATCH');
$app->match('/blog', function () {
// ...
})
->method('PUT|POST');

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.

$app->get('/user/{id}', function ($id) {
// … some code lines
})->convert('id', function ($id) { return (int) $id; });

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

$app->get('/library/{id}/{isbn}', function ($Id, $isbn) {
// ...
})
->assert('Id', '\d+')
->assert('isbn’', '\d+');

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.

$app->get("/", "MyApp\Controller\HomeController::index"); 

After this, You can create  an object for this controller

use Silex\Application;
use Symfony\Component\HttpFoundation\Request;
namespace MyApp
{
class HomeController
{
public function newfunction(Request $request, Application $app)
{
// ...
}
}
}

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,

$app ->register(new Siles\Providers\TwigServiceProvider. [
‘twig.path’ => __DIR__ . ‘/../views;’
])

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

$app->get(‘/’function(){
   return $app['twig']->render('home.twig');
});

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,

$app->before(function (Request $request, Application $app) {
// ...run the request before controller is executed
});

$app->after(function (Request $request, Response $response) {
// ...allows to pull response before sending to client
});

$app->finish(function (Request $request, Response $response) {
// ...execute task after the response have been sent
});

Route Middleware:

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

$app->get('/somewhere', function () {
// … some action code
})
->before($before);
$app->get('/somewhere', function () {
// ...
})
->after($after);

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.

Share your opinion in the comment section. COMMENT NOW

Share This Article

Launch PHP websites without the worry of Server Management.

Pre-Installed Optimized Stack with Git, Composer & SSH

Shahroze Nawaz

Shahroze is a PHP Community Manager at Cloudways - A Managed PHP Hosting Platform. Besides his work life, he loves movies and travelling. You can email him at shahroze.nawaz@cloudways.com

Get Our Newsletter
Be the first to get the latest updates and tutorials.

Do you like what you read?

Get the Latest Updates

Share Your Feedback

Please insert Content

Thank you for your feedback!

BFCM 2019