Getting started with Slim PHP framework by building a very simple MVC/OOP app

Getting started with Slim PHP framework by building a very simple MVC/OOP app

<strong>Getting started with Slim PHP framework by building a very simple MVC/OOP app ... We are going to build a Slim application that creates a farm pen and outputs the noises that the cow &amp; chicken ... Must implement an MVC approach (help us understand how models, views and controllers work together)</strong>

Getting started with Slim PHP framework by building a very simple MVC/OOP app ... We are going to build a Slim application that creates a farm pen and outputs the noises that the cow & chicken ... Must implement an MVC approach (help us understand how models, views and controllers work together)

Aim:

We are going to build a Slim application that creates a farm pen and outputs the noises that the cow & chicken inside the pen make.

Requirements:

  • A pen can only contain a cow and a chicken (will help us practice with slim dependancy injection container)
  • Must implement an MVC approach (help us understand how models, views and controllers work together)

1. So we are gonna need the slim skeleton application - open your command line and run:

composer create-project slim/slim-skeleton slimFarm

  • if you don’t have composer installed globally use the composer documentation to get it

2. On your command line navigate (cd) into slimFarm directory that has been made for you

3. We are going to run a php server so we can see that the slim app is present and working

  • In your command line run: php -S 0.0.0.0:8080 -t ./public/

4. Go to http://0.0.0.0:8080/ to check its working (you should get the slim default page)

5. Open files in your text editor and make a Classes folder inside src

6. Add your namespace to autoloading in composer.json:

"autoload": {
  "psr-4": {
    "Farm\\": "src/classes/"
  }
},

  • n.b: this is in addition to the already existing autoload-dev
  • This will mean we can reference our classes using namespaces rather than having loads of require’s everywhere.

7. Open a new tab in your command line and run composer dump-autoload in the command line

  • This regenerates our autoloading and namespaces to contain the changes we just made in step 6.

8. We need our Cow and Chickens to go in the pen! so make our classes inside Classes/Models folder:

namespace Farm\Models;

class ChickenModel { public $speak = 'cluck'; }

namespace Farm\Models;

class CowModel { public $speak = 'moo'; }

9. Create a Pen class inside Classes/Models folder:

namespace Farm\Models;

class PenModel
{
    public $cow;
    public $chicken;

public function __construct($cow, $chicken)
{
    $this-&gt;cow = $cow;
    $this-&gt;chicken = $chicken;
}

public function getCowNoise(){
    return $this-&gt;cow-&gt;speak;
}

public function getChickenNoise(){
    return $this-&gt;chicken-&gt;speak;
}

}

10. Lets make a factory so that Pen can be created quickly with its dependencies in just one call.

  • Make a Factories folder (inside the Classes folder)
  • Make PenModelFactory:
namespace Farm\Factories;

class PenModelFactory { function __invoke() { $cow = new \Farm\Models\CowModel(); $chicken = new \Farm\Models\ChickenModel(); return new \Farm\Models\PenModel($cow, $chicken); } }

  • Our factory doesn’t need a constructor function, the logic is put inside the __invoke magic method because of the way it is called from our Dependency Injection Container (DIC)

11. So now we have made our factory let’s put it in our DIC

  • Think of the DIC as a big associative array that knows how to instantiate objects for you we put in there for use later in our application
  • Open up src/dependancies.php
  • There are preexisting things inside the DIC already
  • Add our factory like this:
$container['penModel'] = new \Farm\Factories\PenModelFactory();

  • We are saying “inside our container (DIC) add a new key of ‘penModel’ and when we ask for that ‘penModel’ run our factory to instantiate and return a ready made pen object with all the dependencies (cow + chicken) taken care of.”

12. Let’s look in our routing file to see how we deal with different HTTP Requests to our application.

  • Like the defaults already written in here we could use quick anonymous functions to save having to create a factory but we instead are gonna “do it right” so we will make a route and use a controller to call our business logic.
  • Delete the existing $app->get(…) routes already in the file (we will create our own)
  • Set up our route:
$app->get('/makeMeAPen', <where our callback will go> );

  • /makeMeAPen is the URL extension people are expecting to visit to run our code
  • But we don’t have a controller yet so…

13. Let’s make a controller to call our PenFactory and render out a view:

  • Create a Controllers directory inside src/Classes
  • Create PenController inside src/Classes/Controllers/
namespace Farm\Controllers;

class PenController { protected $container;

//this constructor passes the DIC in so we can get our PenFactory out of it later
function __construct($container)
{
    $this-&gt;container = $container;
}

function __invoke($request, $response, $args)
{
    //create our pen from Penfactory in DIC
    $pen = $this-&gt;container-&gt;get('penModel');

    //assign args (variables that will be available on rendered view)
    $args['cowNoise'] = $pen-&gt;getCowNoise();
    $args['chickenNoise'] = $pen-&gt;getChickenNoise();

    //get the default template renderer out of DIC and pass the response and $args to a template file
    return $this-&gt;container-&gt;get('renderer')-&gt;render($response, 'showFarm.phtml', $args);
}

}

14. Now our controller exists lets add it in as the thing that happens when our route is hit:

$app->get('/makeMeAPen', \Farm\Controllers\PenController::class);

15. Notice in our PenController we are calling a template file that doesn’t exist yet so lets create it:

  • Create showFarm.phtml in /templates folder
  • Use the values you put into the $args associative array as normal variables:
<!DOCTYPE html>
<html>
    <head>
        <title>slimFarm</title>
        <style>
            h2 {
                font-size: 10rem;
                color: red;
            }
        </style>
    </head>
    <body>
            <h2>Cows go: <?php echo htmlspecialchars($cowNoise); ?>!</h2>
            <h2>Chickens go: <?php echo htmlspecialchars($chickenNoise); ?>!</h2>
    </body>
</html>

16. Navigate to http://0.0.0.0:8080/makeMeAPen and behold the brilliance of your super advanced app!

php

Bootstrap 5 Complete Course with Examples

Bootstrap 5 Tutorial - Bootstrap 5 Crash Course for Beginners

Nest.JS Tutorial for Beginners

Hello Vue 3: A First Look at Vue 3 and the Composition API

Building a simple Applications with Vue 3

Deno Crash Course: Explore Deno and Create a full REST API with Deno

How to Build a Real-time Chat App with Deno and WebSockets

Convert HTML to Markdown Online

HTML entity encoder decoder Online

Hire Dedicated PHP Developer

Looking to hire affordable yet experienced PHP developers? **[Hire Dedicated PHP Developer](https://hourlydeveloper.io/hire-dedicated-php-developer/ "Hire Dedicated PHP Developer")**, who can convert your idea to reality, within the stipulated...

PHP Web Application Development Company

As a top **PHP Web Application Development Company in USA**[https://www.dataeximit.com/php-development-services/](https://www.dataeximit.com/php-development-services/ "https://www.dataeximit.com/php-development-services/"), we at Data EximIT have...

How to use highchart in php with example

Here, i will let you know that how to use highchart in php application with example. Highchart provides feature to draw different type of charts.

Advantages of Hiring PHP Developer for your Website Project

PHP - Hypertext pre-processor, a scripting language used by many people in developing web pages, but most of us are unaware even of the full form. To train someone and make them learn this whole language is as difficult and time-consuming as it is...

PHP Website Development

Skenix Infotech is a leading PHP Web Development Company that helps companies get results with industry best practices. Get affordable PHP Development Services.