Add a new class with constructor in PHP - DI (PHP configuration format )

Hey Peeps,

I just started with this so don’t burn me :). I want to use PHP-DI with a PHP configuration format. But this class has a constructor (where you need to add values to the class).

For example. I have made a config.php file with this in it.

<?php
return [
    'smush' => new \ReSmush\Helpers\Smushers\Resmush(),
];

Now I want to build the container using this

$containerBuilder = new \DI\ContainerBuilder();

$containerBuilder->addDefinitions('config.php');
$containerBuilder->build();

How can I can I call the container / class?

The class looks like this


class Resmush extends SmushApi
{

    public function __construct($imageType, $imageFile)
    {
        $this->image->type = $imageType;
        $this->image->file = $imageFile;
        $this->url = 'http://api.resmush.it/?qlty=';
        $this->exif = true;
    }

}

I don’t think those parameters should be in the class constructor, since they’re not something the class in it’s entirety should know.

I would do it something like this:

class Resmush extends SmushApi
{
    public function __construct()
    {
    }

    public function reSmushImage($imageFile)
    {
        // imageType is not needed because there functions to get the image type from the file
    }
}

And then you don’t need to pass any constructor parameters.

As for the container you should be able to do it like this:

$containerBuilder->addDefinitions('config.php');
$container = $containerBuilder->build();

$service = $container->get('smush');

One tip though, is would recommend to use a factory to make the container lazy (so that it won’t instantiate the class when you don’t ask for it).

<?php
return [
    'smush' => function() { 
        return new \ReSmush\Helpers\Smushers\Resmush();
    },
];
1 Like

I did not have time to look into it yet, anyway thanks :slight_smile: :netherlands:

What do you mean with this :question: :slight_smile:

non-lazy services will be created always in the container, regardless if you use them or not

Lazy services are only created if and when you use them (i.e. when you call $container->get('some_service'), otherwise (i.e. when your code never calls $container->get('some_service')) they won’t be created, saving CPU time and memory

1 Like

Okay in the example above is it non-lazy or lazy loaded (:question:)

I only load the $service = $container->get('smush'); when I need it.

In your example it is not lazy, in my example it is.

1 Like

Thank you :):rofl::upside_down_face:

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.