Want to Contribute to us or want to have 15k+ Audience read your Article ? Or Just want to make a strong Backlink?

Build Your Own PHP Framework Step By Step – Part 1

On this information, we’ll go over the way you how one can construct your individual PHP framework, with alot much less code than you could be anticipating. You do not want a sophisticated understanding of PHP, though it is going to assist. The code is pretty uncomplicated and easy to know, so this information must be appropriate for many expertise ranges.

Again within the previous days, PHP had no frameworks. The code was clunky and had no strucutre. Software and mannequin code was combined in with the views. The code for the primary model of Fb, which has since been leaked to the online was like this. For those who search the online, you’d in all probability capable of finding a replica with out an excessive amount of effort, however I wont hyperlink to it right here.

From these darkish ages, alongside got here frameworks. Frameworks allow you to cut up your software, mannequin and examine code into separate layers and supply a fundamental construction on your code.

Most PHP initiatives use one of many well-liked frameworks, like Symfony or Zend. However like all “good” issues in life, utilizing a framework another person constructed has downsides.

  • Most frameworks come packaged with a lot of libraries that you’ll by no means use
  • Frameworks lock you in and are troublesome emigrate away from and improve. Strive upgrading from Zend 1 to the most recent model, or Yii 1 to Yii 2. Or from Symfony to Zend or vice versa.
  • Frameworks encourage Framework particular code for frequent operations like getting GET/POST enter and validation, when you might be utilizing framework agnostic code constructed into PHP, or composer dependencies. This makes lock in worse and makes upgrades and switching frameworks even tougher.
  • Frameworks comprise alot of additional processing that you simply in all probability do not want and this has a siginficant efficiency influence.
  • You may be utilizing the libraries that the framework maintainer likes, moderately than those you want. Want RedbeanPHP as your ORM when the framework makes use of Doctrine? You may have to go in opposition to the framework to implement what you need.
  • Including new folks to your group is tougher, you want individuals who have labored with the particular third social gathering framework you’re utilizing. In any other case, they’re going to have to be taught it on the job.
  • The documentation of most frameworks will not be in state and there are alot of undocumented quirks you would possibly run into.

However we nonetheless want a framework, in any other case had been again to the unhealthy previous days of spaghetti code. Whats the answer? Construct your individual light-weight framework!.

The rationale why many frameworks include a lot bloat is that they had been initially created in a world earlier than composer, so the framework tried to offer the whole lot you would possibly ever want.

Nowdays, we have now composer for PHP. As a substitute of getting a framework that gives a lot of libraries that add bloat to your codebase and that you could be by no means use, you’ll be able to individually set up composer packages as wanted. composer additionally offers a free PSR autoloader you need to use to construction your code.

There isn’t a extra want to make use of a 3rd social gathering framework. composer dependencies and inbuilt PHP performance present the whole lot it’s good to create your individual framework with a minimal quantity of code.



Conditions

To construct a fundamental MVC framework with PHP, you will want

  • PHP 8.1 or later
  • composer for dependencies. As you will not be utilizing a pre-built framework, you may solely set up the dependencies you may be utilizing and nothing else.



Arrange composer

To construct your individual PHP framework, you may have to get some dependencies from composer.

Create a composer.json file with the next contents.

{
    "title": "cipher-code/phpframework",
    "description": "PHP Framework",
    "kind": "undertaking",
    "license": "MIT",
    "autoload": {
        "psr-4": {
            "Framework": "src/"
        }
    },
    "require": {
        "slim/slim": "4.11.0",
        "slim/psr7": " ^1.6",
        "php-di/php-di": "^6.4"
    }
}
Enter fullscreen mode

Exit fullscreen mode

Then run composer set up to put in the preliminary dependencies and initialize your autoloader.



Arrange preliminary public/index.php

Like most PHP purposes, you may want a index.php script because the “Entrance Controller” or entry level into your software.

Create the file public/index.php with the next contents.

<?php
// public/index.php
use PsrHttpMessageResponseInterface as Response;
use PsrHttpMessageServerRequestInterface as Request;
use SlimFactoryAppFactory;
use DIContainer;

// This may make referencing information by path a lot less complicated
$rootDir = realpath(__DIR__ . '/..');
outline('ROOT_DIR', $rootDir);

require ROOT_DIR . '/vendor/autoload.php';

$app = AppFactory::create();

$container = new Container();

$app->get('/hey/{title}', operate (Request $request, Response $response, array $args) {
    $title = $args['name'];
    $response->getBody()->write("Whats up, $title");
    return $response;
});

$app->run();
Enter fullscreen mode

Exit fullscreen mode

First, we outline ROOT_DIR as a continuing with we are able to use to discuss with all different in codebase file paths sooner or later. No extra doing __DIR__ . '/../../../Folder/file.php. You may simply begin from ROOT_DIR as a substitute, i.e. ROOT_DIR . '/Folder/file.php.

We then use this ROOT_DIR fixed to load composer. Behind the scenes, composer then units up the autoloader for you so you’ll be able to namespace your code.



The Router

A core part of any framework is the Router, which is used to dispatch incoming requests to the fitting controller motion. That is how Symfony and Zend would possibly know methods to route /hey/{title} to HelloController->hey() for instance.

To construct your individual PHP framework, you want a Router.

We have put in Slim, a brilliant light-weight framework. In our code, we’re solely utilizing the Slim Router to arrange the /hey/{title} route. Slim is not a full MVC framework, it simply offers a fundamental set of core parts reminiscent of a Router, which you need to use to create your individual framework.

This is not but a full MVC framework, as a result of its simply utilizing a easy callback and does not have any Controllers but. Nevertheless, its sufficient to check our setup to ensure the whole lot is wired up correctly.



Affirm setup with the PHP inbuilt net server

Begin the PHP inbuilt net server with

php -S localhost:8080 -t public public/index.php
Enter fullscreen mode

Exit fullscreen mode

Then hit http://localhost:8080/hey/<your title> in your browser.

It is best to see a web page just like the one beneath. If not, return and verify over your work.



Create src/Controller/HelloController.php

As talked about earlier, we’re utilizing a easy callback to answer requests, so this is not a full MVC framework. The subsequent step is so as to add a controller. So, lets add HelloController to deal with requests to /hey/{title}.

<?php
namespace FrameworkController;

use SlimPsr7Request;
use SlimPsr7Response;

class HelloController
{
    public operate hey(Request $request, Response $response, array $args) {
        $title = $args['name'];
        $response->getBody()->write("Whats up, $title");
        return $response;
    }
}
Enter fullscreen mode

Exit fullscreen mode



Wire up your Controller

Replace index.php to match the next. Remember to import the brand new namesapces!

<?php
// public/index.php
use PsrHttpMessageResponseInterface as Response;
use PsrHttpMessageServerRequestInterface as Request;
use SlimFactoryAppFactory;
use DIContainer;
use FrameworkControllerHelloController;

// This may make referencing information by path a lot less complicated
$rootDir = realpath(__DIR__ . '/..');
outline('ROOT_DIR', $rootDir);

require ROOT_DIR . '/vendor/autoload.php';

$app = AppFactory::create();

$container = new Container();

$app->get('/hey/{title}', operate (Request $request, Response $response, array $args) use ($container) {
    /** @var FrameworkControllerHelloController */
    $helloController = $container->get(HelloController::class);
    return $helloController->hey($request, $response, $args);
});

$app->run();
Enter fullscreen mode

Exit fullscreen mode

Right here, we’re utilizing PHP-DI Autowiring to get the controller with $container->get(HelloController::class), as a substitute of calling new HelloController(), which you would possibly attempt to do if I did not let you know in any other case. That is in order that we are able to inject dependencies with Dependency Injection in a while.

Now begin the PHP inbuilt net server once more. Hit http://localhost:8080/hey/<your title> once more and you need to see the identical end result as earlier than. If not, return and verify over your work.



Create src/Util/Greeter.php

Now we have now a controller to dispatch requests, however we have now a design difficulty.

Our controller is doing an excessive amount of. Not solely is it dealing with the output of the greeting, its additionally producing it itself! We must be following SOLID Principles and certainly one of these is Single Objective.

Proper now, the greeting is not too sophisticated and solely helps English. Lets think about a future the place it’s good to do the greetings in a number of languages!. With the present setup, meaning introducing a lot of logic into your code. If $language is Spanish, output the Spanish greeting and so forth.

The controller would get alot larger than it must be. An excellent precept to comply with with any framework is “skinny controllers”. So, you solely put the minimal quantity of code in your controller to deal with the request. The heavy lifting must be performed elsewhere.

If we offload the greeting technology to a different class, we are able to use that as a base for a future construction the place we are able to simply assist a number of languages with out a lot logic.

So, lets offload producing the greeting to a brand new Greeter class.

<?php
// src/Util/Greeter.php
namespace FrameworkUtil;

class Greeter
{
    public operate greet(string $title) : string
    {
        return "Whats up, $title";
    }
}
Enter fullscreen mode

Exit fullscreen mode

Replace HelloController to make use of Greeter.

<?php
// src/Controller/HelloController.php
namespace FrameworkController;

use FrameworkUtilGreeter;
use SlimPsr7Request;
use SlimPsr7Response;

class HelloController
{
    public operate __construct(
        protected Greeter $greeter
    ) {}

    public operate hey(Request $request, Response $response, array $args) 
    {
        $title = $args['name'];
        $response->getBody()->write($this->greeter->greet($title));
        return $response;
    }
}
Enter fullscreen mode

Exit fullscreen mode

That is our first use of Dependency Injection. Within the constructor, we use PHP property promotion so we solely should outline the dependency as soon as. PHP-DI Autowiring makes use of Reflection to verify what the category wants forward of time, then injects it robotically at runtime.

This makes managing dependencies and adhering to SOLID Ideas a lot simpler.



Wrapping up Half 1

Now you’ve a easy framework with a Router, DI and a Controller. It’s largely following SOLID Ideas and we haven’t any exams but.

To implement full MVC, we’d like a Mannequin and View layer. This may come subsequent in “Construct Your Personal PHP Framework – Half 2”. If you would like to present me further motivation to create Half 2 sooner, share this text throughout all your socials utilizing the hyperlinks supplied. The extra engagement I see, the quicker i will create Half 2!.

Add a Comment

Your email address will not be published. Required fields are marked *

Want to Contribute to us or want to have 15k+ Audience read your Article ? Or Just want to make a strong Backlink?