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 Programming Language - PHP Tutorial for Beginners

Learn the PHP programming language in this full course / tutorial. The course is designed for new programmers, and will introduce common programming topics using the PHP language.



Learn More

PHP for Beginners - Become a PHP Master - CMS Project

Python and PHP Programming Bundle

How to build a Laravel REST

Build a Basic CRUD App with Laravel and Vue

PHP OOP: Object Oriented Programming for beginners + Project

Write PHP Like a Pro: Build a PHP MVC Framework From Scratch

The Complete PHP MySQL Professional Course with 5 Projects

Learn PHP Programming From Scratch

Course developed by Mike Dane. Check out his YouTube channel for more great programming courses: https://www.youtube.com/channel/UCvmINlrza7JHB1zkIOuXEbw

Learn PHP Programming - PHP Tutorial for for Absolute Beginner

Learn PHP Programming - PHP Tutorial for for Absolute Beginner

Learn PHP Programming - PHP Tutorial for for Absolute Beginner: Learn PHP Programming For Web Development The Fast And Easy Way! The PHP Programming Language is one of the most POPULAR Web Development Programming Languages for a reason. In this course I'll show you why!

Learn PHP Programming For Web Development The Fast And Easy Way!

The PHP Programming Language is one of the most POPULAR Web Development Programming Languages for a reason. In this course I'll show you why!

You don't need any prior knowledge of coding or web development to take this course. We'll download all the tools you'll need for free, and I'll walk you through setting them up. Then we'll dive right in and start learning the PHP language.

This is the course for you if you're interested in becoming a web developer and maybe don't know where to start. It's also great if you're already a front end developer, but want to add some serious skills to your tool belt. Since PHP powers Wordpress, this course is also great if you'd like to really customize your Wordpress sites (we don't discuss wordpress in this course, but if you understand PHP, you can understand what's going on behind the scenes in Wordpress just by diving into the code and checking it out on your own).

What you’ll learn

  • How To Download and Use WAMP Server
  • How To Run PHP Locally on your Computer
  • Basic PHP Programming Concepts Like Variables, Data Types
  • Math Operators, Assignment Operators, Comparison Operators
  • How To Do If/Else Statements and Why They're Important
  • How To Loop Using While Loops, For Loops, and Foreach Loops
  • Understanding Indexed Arrays and Why They Are So Great
  • Understanding Associative Arrays (called Hashes or Dictionaries in other Languages)
  • All About Functions - Mini Programs Inside Your Program
  • We'll Build a FizzBuzz app!
  • PHP For Web Development
  • Including PHP on a web page
  • Requiring Things on a Web Page With PHP
  • Using Web Forms With PHP
  • Processing Form Data With PHP
  • And More!

Thanks for reading

If you liked this post, share it with all of your programming buddies!

Follow us on Facebook | Twitter

Further reading about PHP

Build a Basic CRUD App with PHP and MySQL

Build a CRUD Operation using PHP & MongoBD

Laravel 5.8 Tutorial from Scratch for Beginners

Token Authentication in PHP

PHP Interview Questions - Top 50 Questions for PHP Developers

PHP Tutorial for Beginners

100+ PHP Interview Questions - Interview Questions On PHP 2019 - Online...

With the modernization of the world, everyone is trying to seek knowledge in the field of digital marketing to place his or her steps with the world. In today’s technology-driven world, organizations have achieved digital benefits to increase their demand and profit. But, to achieve this goal, it is quite important to make the sites user-friendly and highly-interactive. For this, only PHP language can fulfill these objectives. Go for PHP without any fear and become the mastermind in that field. If you are PHP lover, then you are in the right place. Read the full article if you want to know about the scope and career in the PHP language.

With the modernization of the world, everyone is trying to seek knowledge in the field of digital marketing to place his or her steps with the world. In today’s technology-driven world, organizations have achieved digital benefits to increase their demand and profit. But, to achieve this goal, it is quite important to make the sites user-friendly and highly-interactive. For this, only PHP language can fulfill these objectives. Go for PHP without any fear and become the mastermind in that field. If you are PHP lover, then you are in the right place. Read the full article if you want to know about the scope and career in the PHP language.