create account

Create MVC(Model View Controller) Structure in Slim Microframework part-1 by alfarisi94

View this thread on: hive.blogpeakd.comecency.com
· @alfarisi94 · (edited)
$30.87
Create MVC(Model View Controller) Structure in Slim Microframework part-1
![Screenshot_31.png](https://res.cloudinary.com/hpiynhbhq/image/upload/v1521043633/lwuhimtdsdrwqb3z5rst.png)

This tutorial we will learn how to set the structure of slim applications, if we want to build a full web application, not just as a RestApi. So the purpose of this tutorial gives you an idea of ​​making the MVC system in Slim. Because when we use slim, slim does not come with MVC system, therefore for those of you who want to use Slim as full web application, you will be very helpful with this tutorialjust start we start this tutorial.

#### What Will I Learn?
- Create a View and Controller Structure in Slim
- Use Psr-4 Autoload
- Inject Container in Controller
- Use Templating Twig and Combine With Routing System

#### Requirements
- Install Slim >= 3.0
- Localhost (xampp,wampp or etc)
- Intermediate OOP PHP

#### Difficulty
- Intermediate


### Preparation
Before you start the following slim MVC tutorial, make sure you have learned basic slim. I have listed it in the curriculum section .Cause I will not explain it from the beginning.Slim structure is very flexible, slim structure that I make is the best in my opinion. You can make this tutorial as a reference to create your own MVC system.

<li><b>Make Structure File</b></li>
I will create some basic folders that will allow us to share the files.

<b>1. Public folder</b>

In the public folder I will create the <b>index.php</b> and <b>.htaccess</b> files .

![Screenshot_19.png](https://res.cloudinary.com/hpiynhbhq/image/upload/v1520959954/lcap78zecyzatq9orbbi.png)


<li>index.php</li> 
index.php is the main file that we first access when opening slim applications. in this file i will load some important files. which I will make later
<pre>
<code>
<?php
require '../bootstrap/app.php';
require '../bootstrap/container.php';
require '../routes/web.php';
$app->run();
</code>
</pre>
<code>require '../bootstrap/app.php';</code> : I will load all the vendors in this file, and put the instance of slim.

<code>require '../bootstrap/container.php';</code> : I will put the container I created in the <b>container.php</b> file and I will import in this index.php file.

<code>require '../routes/web.php';</code> :  Import routes in folder routes and file web.php
<li>.htaccess</li>
This file is used to set up its routing system, for you who do not know .htacces. I've covered this in his tutorial before in the tutorial section. useful for pretty url.
<pre>
<code>
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^ index.php [QSA,L]
</code>
</pre>

<b>2. Bootstrap Folder</b>

I will create a folder called bootstrap. this is not the bootstrap name of the css framework. 
in the bootstrap folder I will create two files <b>app.php</b> and <b>container.php</b>.

![Screenshot_20.png](https://res.cloudinary.com/hpiynhbhq/image/upload/v1520961106/kwnuglflkmeyiqt4x48c.png)

<li>app.php</li>
This file serves to load all existing vendors in slim applications, and become an instance of slim.
<pre>
<code>
<?php
require __DIR__ .'/../vendor/autoload.php';
$app = new Slim\App([
	'settings' =>[
		'displayErrorDetails'=>true
	]
]);
</code>
</pre>
<code>require __DIR__ .'/../vendor/autoload.php';</code> : To load all file in vendor with <b>autoload.php</b>.

<code>'settings' =>[
		'displayErrorDetails'=>true
	]</code> : To show error if there is an error. This setting for development mode only

<li>container.php</li>
In the container.php file is all container in the list before the use in seluru slim application. in this session we have not registered any containers, we will start using this file in the View section.

<b>3. Routes Folder</b>

In the folder section of the routes, in accordance with its name, this file contains all the routes in our slim application. in the routes folder, We have <b>web.php</b>

![Screenshot_21.png](https://res.cloudinary.com/hpiynhbhq/image/upload/v1520962105/ys2einzu7jxksndlw8ae.png)
<li>web.php</li>
in this file all routers are registered.
<pre>
<code>
<?php
$app->get('/', function(){
return "Hello , I'm Slim MVC";
});
</code>
</pre>
 So far we will check whether the folder structure that we created is correct. I will check the routing <code>$app->get('/', function(){}</code> and will return the value <code>return "Hello , I'm Slim MVC";</code>. If it does not happen error then we will see its result like this .

![Screenshot_22.png](https://res.cloudinary.com/hpiynhbhq/image/upload/v1520962652/toa55pmy2chcwt0fuegc.png)

### Make View of MVC Structure
In this section I will create 'V' in MVC structure. i will use template system from twig. so. the first step that we will do we must create a container for view twig.
<li><b>Install Twig</b></li>
The first step I will install twig, run the command prompt in your project folder.
<code>composer require slim/twig-view</code>

![Screenshot_23.png](https://res.cloudinary.com/hpiynhbhq/image/upload/v1520999508/szdq8x2ookgya0hbpars.png)

Well now we have installed twig in our application. but to use it we have to register it in <b>app/container.php</b>. Because we have determined that every container we create must be registered in <b>container.php</b> file.

<li><b>Register Container</b></li>
The twig container register in the <b>container.php</b> file
<pre>
<code>
<?php
$container = $app->getContainer();
//container twig view
$container['view'] = function ($container) {
    $view = new \Slim\Views\Twig(__DIR__.'/../resources/views', [
        'cache' => 'path/to/cache'
    ]);
    // Instantiate and add Slim specific extension
    $basePath = rtrim(str_ireplace('index.php', '', $container['request']->getUri()->getBasePath()), '/');
    $view->addExtension(new Slim\Views\TwigExtension($container['router'], $basePath));
    return $view;
};
</code>
</pre>
<code>$container = $app->getContainer();</code> : This function is used to load all container 
which has been registered.

It is important to remember<code>__DIR __. '/ .. / resources / views'</code> is our view file directory. so make sure your directory points to the correct folder.  in this tutorial I will put my view in the <b>resources / views /</b>

<li><b>Create Folder Resources</b></li>
After we register the container twig, We will create a folder that I named the <b>resources</b> and in it I create a folder again with the name <b>views</b>. so later all view twig will be there, more structured and easier to set.

![Screenshot_24.png](https://res.cloudinary.com/hpiynhbhq/image/upload/v1521001660/u7prlwpzz5cpjudqzhju.png)

<li><b>Use Twig</b></li>
To use twig we have to use in web.php file <b>(routes/web.php)</b>.
<b>web.php</b>
<pre>
<code>
<?php
$app->get('/', function($request,$response){
return $this->view->render($response,'home.twig');
});
</code>
</pre>
<code>return $this->view->render($response,'home.twig');</code> : We can use twig in this way, <b>this-> view</b> is the name of the key we registered in the container. <b>render()</b> is used to render twig view. I have created a home.twig file its contents very simple just to test whether our templating system is sync with routes.

<b>home.twig</b>

``` html
<h3>I'm templating from twig and I'm integrated with the route system</h3>
```
![Screenshot_25.png](https://res.cloudinary.com/hpiynhbhq/image/upload/v1521002394/udxedotvxa4k5zpktehq.png)

If there is no error then you will see the  home.twig file renderred well.

### Make Controller of MVC Structure
We get to the controller part, I will start to create controller by creating <b>app</b> folder and inside app folder i will create two folder , they are <b>controllers</b> and <b>models</b>.

![Screenshot_26.png](https://res.cloudinary.com/hpiynhbhq/image/upload/v1521034364/wauv6k8pyx2ow9rzk8nd.png)

Now what is important for us to do is how the controller file in the folder can access in index.php, of course will be tired really if we must require one by one in the <b>index.php</b> . And we also do not know which controllers and models we need. the bigger the application we make will be the bigger the file size. of course this would be a problem to maintain it.  to handle it. I will use <b>psr-4 system</b>.

<li><b>User psr-4</b></li>
To use Psr-4, We must update <b>composer.json</b>
<pre>
<code>
{
    "require": {
        "slim/slim": "^3.9",
        "slim/twig-view": "^2.3"
    },
    "autoload":{
    	"psr-4":{
    		"App\\": "app"
    	}
    }
}
</code>
</pre>
<code>"App\\": "app"</code> : <b>"App\\"</b>is the namespace system we will use. and <b> "app"</b> is the name of the folder that we will load.
Well after we specify its autoload system, we must update composer.json,  in this way :

<code>composer dump-autoload -o</code>

![Screenshot_27.png](https://res.cloudinary.com/hpiynhbhq/image/upload/v1521038611/lorjponww9q95jtwughd.png)

After that I will do a little test to find out if the system psr-4 autoload successful.

<li><b>Make Controller</b></li>

For those of you who do not know at all what a controller is. controller is a bridge between our routing system and also the data. routing will then see what url we access and will determine what controller will be in use. later the controller will determine the response in the form of view or json.

<b>1. Created forumController</b>

Create a controller that is placed in the <b>app-> controllers</b> folder.  the name is <b>forumController</b>.
<pre>
<code>
<?php
namespace App\Controllers;
class forumController{
	public function index(){
		echo "This is from message from forumController";
	}
}</code>
</pre>
<code>namespace App\Controllers;</code> : To user psr-4 autoload.
<code>public function index(){}</code> : This function names that we can use in the route system.

<li><b>Using the Controller in Routes</b></li>
We will use the controller in routes, so we choose what controller will be used for specific routing. Open the web.php file located in the <b>routes->web.php</b> folder.

<br>

<code>$app->get('/forum', 'App\controllers\forumController:index');</code> :  
I added a new routing to test whether the controller is connected to the routing system.
<b>App\controllers\forumController</b>  the controller  directory. and <b>:index</b> is the function name that resides in the forumController.


To test it we can open it on localhost by <b>'/ forum'</b> routing, if it works we will see the contents in the <b>index</b> function in the forumController.

![Screenshot_29.png](https://res.cloudinary.com/hpiynhbhq/image/upload/v1521041593/x3anketcvychkllvtz2f.png)


<li><b>Use Sistem Template Twig in Controller</b></li>
The container view we list will not be known in the controller. because the view or twig is registered in the <b>bootstrap / container.php</b> . whereas our controller does not have the context of container.php to handle it we need to add some settings.
<pre>
<code>
<?php
namespace App\Controllers;
use Interop\Container\ContainerInterface;
class forumController{
	protected $c;
	public function __construct(ContainerInterface $container){
		$this->c = $container;
	}
	public function index($request,$response){
		return $this->c->view->render($response,'home.twig');
	}
}
</code>
</pre>

<code>use Interop\Container\ContainerInterface;</code> : To get access to the container . We use this file.

<pre>
<code>
protected $c;
	public function __construct(ContainerInterface $container){
		$this->c = $container;
	}
</code>
</pre>
<b>protected $c;</b> : Provide a variable that will be used later to accommodate <b>$container</b>. I will put the container in the <b>__construct</b> function. __Construct is the function that will first be called.
Now we can use container view inside the controller this way<b>return $this->c->view->render($response,'home.twig');</b> .
If there is no error then we will see the contents of the <b>home.twig</b>.

``` html 
<h2>Hello world , I'm slim MVC . I'm from Forum Controller</h2>
```

![Screenshot_30.png](https://res.cloudinary.com/hpiynhbhq/image/upload/v1521043183/lu8dmkvelxh6pvzkybze.png)

We finished finishing the mvc structure in slim, but this tutorial only talk about <b>VIEW</b> and <b>CONTROLLER</b>, in part-2 i will discuss more about model, later we will use eloquent on slim in model part. -thank you for following this tutorial. hopefully useful for you. thank you

#### Curriculum

- Templating Twig in Slim https://utopian.io/utopian-io/@alfarisi94/how-to-use-twig-templating-in-slim
- Eloquent in Slim https://utopian.io/utopian-io/@alfarisi94/how-to-use-database-eloquent-in-slim
- Routing System in Slim https://utopian.io/utopian-io/@alfarisi94/how-to-install-slim-and-basic-routing-system-in-slim
- Slim MVC part-2 https://utopian.io/utopian-io/@alfarisi94/create-mvc-model-view-controller-structure-in-slim-microframework-part-2


<br /><hr/><em>Posted on <a href="https://utopian.io/utopian-io/@alfarisi94/create-mvc-model-view-controller-structure-in-slim-microframework-part-1">Utopian.io -  Rewarding Open Source Contributors</a></em><hr/>
👍  , , , , , , , , , , , , , ,
properties (23)
authoralfarisi94
permlinkcreate-mvc-model-view-controller-structure-in-slim-microframework-part-1
categoryutopian-io
json_metadata"{"community":"utopian","app":"utopian/1.0.0","format":"markdown","repository":{"id":926544,"name":"Slim","full_name":"slimphp/Slim","html_url":"https://github.com/slimphp/Slim","fork":false,"owner":{"login":"slimphp"}},"pullRequests":[],"platform":"github","type":"tutorials","tags":["utopian-io","slim","mvc","web","oop"],"users":["alfarisi94"],"links":["https://res.cloudinary.com/hpiynhbhq/image/upload/v1521043633/lwuhimtdsdrwqb3z5rst.png","https://res.cloudinary.com/hpiynhbhq/image/upload/v1520959954/lcap78zecyzatq9orbbi.png","https://res.cloudinary.com/hpiynhbhq/image/upload/v1520961106/kwnuglflkmeyiqt4x48c.png","https://res.cloudinary.com/hpiynhbhq/image/upload/v1520962105/ys2einzu7jxksndlw8ae.png","https://res.cloudinary.com/hpiynhbhq/image/upload/v1520962652/toa55pmy2chcwt0fuegc.png","https://res.cloudinary.com/hpiynhbhq/image/upload/v1520999508/szdq8x2ookgya0hbpars.png","https://res.cloudinary.com/hpiynhbhq/image/upload/v1521001660/u7prlwpzz5cpjudqzhju.png","https://res.cloudinary.com/hpiynhbhq/image/upload/v1521002394/udxedotvxa4k5zpktehq.png","https://res.cloudinary.com/hpiynhbhq/image/upload/v1521034364/wauv6k8pyx2ow9rzk8nd.png","https://res.cloudinary.com/hpiynhbhq/image/upload/v1521038611/lorjponww9q95jtwughd.png","https://res.cloudinary.com/hpiynhbhq/image/upload/v1521041593/x3anketcvychkllvtz2f.png","https://res.cloudinary.com/hpiynhbhq/image/upload/v1521043183/lu8dmkvelxh6pvzkybze.png"],"image":["https://res.cloudinary.com/hpiynhbhq/image/upload/v1521043633/lwuhimtdsdrwqb3z5rst.png","https://res.cloudinary.com/hpiynhbhq/image/upload/v1520959954/lcap78zecyzatq9orbbi.png","https://res.cloudinary.com/hpiynhbhq/image/upload/v1520961106/kwnuglflkmeyiqt4x48c.png","https://res.cloudinary.com/hpiynhbhq/image/upload/v1520962105/ys2einzu7jxksndlw8ae.png","https://res.cloudinary.com/hpiynhbhq/image/upload/v1520962652/toa55pmy2chcwt0fuegc.png","https://res.cloudinary.com/hpiynhbhq/image/upload/v1520999508/szdq8x2ookgya0hbpars.png","https://res.cloudinary.com/hpiynhbhq/image/upload/v1521001660/u7prlwpzz5cpjudqzhju.png","https://res.cloudinary.com/hpiynhbhq/image/upload/v1521002394/udxedotvxa4k5zpktehq.png","https://res.cloudinary.com/hpiynhbhq/image/upload/v1521034364/wauv6k8pyx2ow9rzk8nd.png","https://res.cloudinary.com/hpiynhbhq/image/upload/v1521038611/lorjponww9q95jtwughd.png","https://res.cloudinary.com/hpiynhbhq/image/upload/v1521041593/x3anketcvychkllvtz2f.png","https://res.cloudinary.com/hpiynhbhq/image/upload/v1521043183/lu8dmkvelxh6pvzkybze.png"],"moderator":{"account":"portugalcoin","time":"2018-03-18T11:49:38.343Z","reviewed":true,"pending":false,"flagged":false},"questions":[{"question":"Is the project description formal?","answers":[{"value":"Yes it’s straight to the point","selected":true,"score":10},{"value":"Need more description ","selected":false,"score":5},{"value":"Not too descriptive","selected":false,"score":0}],"selected":0},{"question":"Is the language / grammar correct?","answers":[{"value":"Yes","selected":false,"score":20},{"value":"A few mistakes","selected":true,"score":10},{"value":"It's pretty bad","selected":false,"score":0}],"selected":1},{"question":"Was the template followed?","answers":[{"value":"Yes","selected":true,"score":10},{"value":"Partially","selected":false,"score":5},{"value":"No","selected":false,"score":0}],"selected":0},{"question":"Is there information about the additional frameworks?","answers":[{"value":"Yes, everything is explained","selected":true,"score":5},{"value":"Yes, but not enough","selected":false,"score":3},{"value":"No details at all","selected":false,"score":0}],"selected":0},{"question":"Is there code in the tutorial?","answers":[{"value":"Yes, and it’s well explained","selected":true,"score":5},{"value":"Yes, but no explanation","selected":false,"score":3},{"value":"No","selected":false,"score":0}],"selected":0},{"question":"Is the tutorial explains technical aspects well enough?","answers":[{"value":"Yes, it teaches how and why about technical aspects","selected":true,"score":5},{"value":"Yes, but it’s not good/enough","selected":false,"score":3},{"value":"No, it explains poorly","selected":false,"score":0}],"selected":0},{"question":"Is the tutorial general and dense enough?","answers":[{"value":"Yes, it’s general and dense","selected":true,"score":5},{"value":"Kinda, it might be more generalized","selected":false,"score":3},{"value":"No, it’s sliced unnecessarily to keep part number high","selected":false,"score":0}],"selected":0},{"question":"Is there an outline for the tutorial content at the beginning of the post","answers":[{"value":"Yes, there is a well prepared outline in “What will I learn?” or another outline section","selected":true,"score":5},{"value":"Yes, but there is no proper listing for every step of the tutorial or it’s not detailed enough","selected":false,"score":3},{"value":"No, there is no outline for the steps.","selected":false,"score":0}],"selected":0},{"question":"Is the visual content of good quality?","answers":[{"value":"Yes","selected":true,"score":5},{"value":"Yes, but bad quality","selected":false,"score":3},{"value":"No","selected":false,"score":0}],"selected":0},{"question":"Is this a tutorial series?","answers":[{"value":"Yes","selected":true,"score":5},{"value":"Yes, but first part","selected":false,"score":3},{"value":"No","selected":false,"score":0}],"selected":0},{"question":"Is the tutorial post structured?","answers":[{"value":"Yes","selected":true,"score":5},{"value":"Not so good","selected":false,"score":3},{"value":"No","selected":false,"score":0}],"selected":0}],"score":50}"
created2018-03-14 16:07:42
last_update2018-03-18 11:49:39
depth0
children2
last_payout2018-03-21 16:07:42
cashout_time1969-12-31 23:59:59
total_payout_value21.533 HBD
curator_payout_value9.339 HBD
pending_payout_value0.000 HBD
promoted0.000 HBD
body_length12,995
author_reputation5,678,893,550,406
root_title"Create MVC(Model View Controller) Structure in Slim Microframework part-1"
beneficiaries
0.
accountutopian.pay
weight2,500
max_accepted_payout1,000,000.000 HBD
percent_hbd10,000
post_id44,403,408
net_rshares11,888,645,646,326
author_curate_reward""
vote details (15)
@portugalcoin ·
Thank you for the contribution. It has been approved.

You can contact us on [Discord](https://discord.gg/uTyJkNm).
**[[utopian-moderator]](https://utopian.io/moderators)**
properties (22)
authorportugalcoin
permlinkre-alfarisi94-create-mvc-model-view-controller-structure-in-slim-microframework-part-1-20180318t114944371z
categoryutopian-io
json_metadata{"tags":["utopian-io"],"community":"utopian","app":"utopian/1.0.0"}
created2018-03-18 11:49:45
last_update2018-03-18 11:49:45
depth1
children0
last_payout2018-03-25 11:49:45
cashout_time1969-12-31 23:59:59
total_payout_value0.000 HBD
curator_payout_value0.000 HBD
pending_payout_value0.000 HBD
promoted0.000 HBD
body_length172
author_reputation598,828,312,571,988
root_title"Create MVC(Model View Controller) Structure in Slim Microframework part-1"
beneficiaries[]
max_accepted_payout1,000,000.000 HBD
percent_hbd10,000
post_id45,124,882
net_rshares0
@utopian-io ·
### Hey @alfarisi94 I am @utopian-io. I have just upvoted you!
#### Achievements
- You have less than 500 followers. Just gave you a gift to help you succeed!
- Seems like you contribute quite often. AMAZING!
#### Community-Driven Witness!
I am the first and only Steem Community-Driven Witness. <a href="https://discord.gg/zTrEMqB">Participate on Discord</a>. Lets GROW TOGETHER!
- <a href="https://v2.steemconnect.com/sign/account-witness-vote?witness=utopian-io&approve=1">Vote for my Witness With SteemConnect</a>
- <a href="https://v2.steemconnect.com/sign/account-witness-proxy?proxy=utopian-io&approve=1">Proxy vote to Utopian Witness with SteemConnect</a>
- Or vote/proxy on <a href="https://steemit.com/~witnesses">Steemit Witnesses</a>

[![mooncryption-utopian-witness-gif](https://steemitimages.com/DQmYPUuQRptAqNBCQRwQjKWAqWU3zJkL3RXVUtEKVury8up/mooncryption-s-utopian-io-witness-gif.gif)](https://steemit.com/~witnesses)

**Up-vote this comment to grow my power and help Open Source contributions like this one. Want to chat? Join me on Discord https://discord.gg/Pc8HG9x**
properties (22)
authorutopian-io
permlinkre-alfarisi94-create-mvc-model-view-controller-structure-in-slim-microframework-part-1-20180318t120651889z
categoryutopian-io
json_metadata{"tags":["utopian-io"],"community":"utopian","app":"utopian/1.0.0"}
created2018-03-18 12:06:51
last_update2018-03-18 12:06:51
depth1
children0
last_payout2018-03-25 12:06:51
cashout_time1969-12-31 23:59:59
total_payout_value0.000 HBD
curator_payout_value0.000 HBD
pending_payout_value0.000 HBD
promoted0.000 HBD
body_length1,086
author_reputation152,955,367,999,756
root_title"Create MVC(Model View Controller) Structure in Slim Microframework part-1"
beneficiaries[]
max_accepted_payout1,000,000.000 HBD
percent_hbd10,000
post_id45,127,207
net_rshares0