Start a workflow with Slim Framework (Part 2)

Tram Ho

In the previous post , I briefly introduced about Slim framework as well as some basic setup steps when Slim loves I need something new to install that instead because laravel will always be available waiting for us to call. This article will continue the remaining steps to complete a project with Slim.


Let’s go to create the first route with slim!

Open the configroutes.php file and add the following code.

If anyone already knows laravel, the route declaration is similar to this declaration in laravel so:

If you request to query a page in basepath + '/' format basepath + '/' Slim will use the function to handle two input variables $ request (which contains requests to the server) and $ response (which will handle the return. data of the server). Specifically, $ reponse will print a line of text Hello World!

Good URLs

Note: The public/ directory is just the server’s DocumentRoot directory, but it will never be part of the base path or url.

Bad URLs


slim provides several methods to add controller logic directly in the callback function. The PSR-7 request object is injected into the slim route as the first argument in the callback function.

Let’s review the example route above. Although such a declaration is quite intuitive, it is not suitable for scenarios with complex business logic. Suppose there are dozens or hundreds of routes that need to be registered and processed. Unless your logic is extremely simple, writing logic in this callback can make your route file not clean at all, and really this is not highly recommended. It would be so much better if we could put the logic into individual files just like laravel and the route simply needs to navigate to the correct processing file. That’s why the Single Action Controller is used.

Each Single Action controller will be represented by its own class.

Action action does the following:

  • Collect input from Http Request (If necessary)
  • Call the processing for the input collected in the previous step and keep the result
  • Generate an Http response (usually return the result of the handler)

The logic including input form validate, error handling, etc. will be pushed down to a separate handler or response reder.

A response can be rendered to HTML (usually twig) for a regular web request or JSON for a RESTful API request, etc.

Let’s find out in detail how a stream when calling from the routes to the action will behave.

Web request

Create a subdirectory: src/Action
Create an action class: src/Action/HomeAction.php

Then replace the route handler in configroutes.php with the following handler:

Well with the above steps, instead of you handling the writing Hello World! Right on the route, you will return it to action for processing.

RESTful API request

With RESTful API request, normally my action will be returned as JSON. To write a valid JSON response you can write the string json_encode to the content of the response and set the content-type of the header to application/json :

Open your home page browser and you will get {"success":true}

In case you want to change the status code of the response you just need to use the $response->withStatus(x) .

Above is how to use a basic action, but as I said above, the host action should only perform the input to navigate to the input handler to get that result and return the response. So what is the handling part called by Action?


Well, this is the part that Action calls logic processing as I mentioned above

Forget CRUD, your API will have to do business handling, not just database operations.

You shouldn’t put logic in action. The handler will be action called to the domain, resp, service. If you want to reuse the service with many different actions, you just need to call your service on that action.


As explained above, the service performs the business logic

Create the UserCreator service as below:

Explain through the above code a little bit. It is responsible for handling the logic of receiving input, validate input, if validate fails it will throw a ValidationExceoption error and ask to check the input again, and if the input is valid it will call the repository (the part that works with db) to create a user. new.

And the repository or ValidationException I just mentioned is what we have to go to learn next.


ValidationException will not be something available, but I have to create it:

The ValidationException will have a status code of 422, the messsage and error are the message and the error array. This pattern is called the Notification pattern

If you like this pattern for validation then this library will be highly recommend: selective / validation .


The Repository will be responsible for working with the database.

There are two types of repositories: collection-oriented and persistence-oriented repositories. In this article we will talk about persistence-oriented repositories because they are suitable for handling large amounts of data.

The Repository will be the source of all the data your application needs and it is also the intermediary between the service and the database. A repository improves maintainability, test, and readability by separating the business logic from the data manipulation logic and providing centrally managed and consistently managed access rules for a data source.

Each public repository will represent one query. The return value will represent the result of that query. Transactions will be processed at a higher level as a service but not in the repository.

Let’s try to create a repository that works with the user table.

Run the following sql command to create the user table in your test database

Setting db connection

Note : Use PDO and SQL here only for learning purposes. In a practical application, using SQL QuickBuilder would be recommended as it would be helpful in maintenance and security.

Insert the definition for PDO :: class into container: config/container.php

From now on, PHP-DI will always be injected with the PDO instance as soon as we declare the PDO in the constructor as dependency.

Create the directory src/Domain/User/Repository Create the file src/Domain/User/Repository/UserCreatorRepository.php and add the code.

Note PDO class declaration is required for all repositories because it contains the code to connect db and of course the repository is the part that must manipulate db.

Finally, we declare to add a single route Post method to create the user

And UserCreateAction class will be defined as follows:

This paragraph will take the input from the request and pass it down to the service and as above explained the service performs the validation and insert new records into the db by calling the repository. And finally return the bold reponse json.

So we have finished understanding a workflow of the request. The directory structure will take the form

Good luck.


Share the news now

Source : Viblo