Skip to main content
2 of 2
added 60 characters in body; edited title
Jamal
  • 34.9k
  • 13
  • 133
  • 237

Wiring classes together in PHP

I've created a base structure for my project and found a way to wire classes together, I create an array of previously loaded classes and call them from the cache. I then have a static class that holds the cache and I call the static class when I need a class.

I feel that there is a much better way to do this, and maybe I'm doing something extremely wrong? How do other PHP applications do this? I'm pretty new to it, so I was wondering if anyone could advise me towards a better way to do this? It feels like it could be hugely improved.

Current directory structure:

enter image description here

The static class, I use this to get my classes (providers, I call them):

<?php declare(strict_types = 1);

namespace App;

class App {
    private static $providers = array();

    public static function getProvider($provider) {
        if (!isset(self::$providers[$provider])) {
            $providerName = 'App\Providers\\' . $provider;
            self::$providers[$provider] = new $providerName();
        }

        return self::$providers[$provider];
    }
}

Example of how I use it, I do this in all my controllers to show a view:

<?php declare(strict_types = 1);

use App\App;

namespace App\Controllers\Frontend\Guest;

class LoginController 
{
    public function getView() 
    {
        \App\App::getProvider('Template')->renderTemplate('index.html');
    }
}

Here is one of my few providers:

<?php declare(strict_types = 1);

namespace App\Providers;

class Template {
    private $twig;

    public function __construct() {
        $this->twig = new \Twig_Environment(new \Twig_Loader_Filesystem(ROOT . '/resources/templates'), array(
            'cache' => ROOT . '/storage/cache/templates',
        ));
    }

    public function renderTemplate($template) {
        echo $this->twig->render($template, array('the' => 'variables', 'go' => 'here'));
    }
}