CrazeD
CrazeD

Reputation: 535

How to access libraries inside a controller?

I'm building a small framework that I can use for repeated mundane stuff on future small projects.

I'm stuck on the best way to access libraries from inside a controller. I originally implemented a system similar to CodeIgniter's whereby my main controller class is basically a super object and loads all the classes into class variables which are then accessed by extending the controller and doing like $this->class->method()

I find that a little ugly, though. So I thought of just loading each class individually on a per-use basis in each controller method.

What's the best (cleanest) way of doing this?

Upvotes: 2

Views: 144

Answers (3)

Chris Tickner
Chris Tickner

Reputation: 2017

To only ever have one instance of each class, you could create a simple service container.

class ServiceContainer
{
    protected $services;

    public function get($className)
    {
        if (!array_key_exists($className, $this->services)) {
            $this->services[$className] = new $className;
        }

        return $this->services[$className]
    }
}

Then create one ServiceContainer instance per application. Inject the container into all of your controllers and use

public function someAction()
{
    $this->container->get('Mailer')->send($email_data);
}

Simple example, and obviously needs a lot of work to make useable (for instance autoloading needed and handling of file paths for ease of use, or easier way to add services without getting them, etc).

Upvotes: 2

cmbuckley
cmbuckley

Reputation: 42488

PHP provides autoload functionality with SPL and spl_autoload (and related functions). You can register a custom autoloader for your library code.

For the shared functionality handled by your application, have you considered the Front Controller design pattern?

Upvotes: 2

prodigitalson
prodigitalson

Reputation: 60403

I dont like the way CodeIgniter does it. Its never seemed right to me. I favor an auto loading class pushed onto the spl_autoload stack. And then just calling the class as normal like:

$class = new SomeClass();

Upvotes: 2

Related Questions