# Simple example of DI autowiring in Laminas MVC

**URL:** <https://discourse.laminas.dev/t/simple-example-of-di-autowiring-in-laminas-mvc/3291>\
**Category:** Components & MVC\
**Tags:** laminas-di\
**Created:** [April 14, 2023, 5:55pm UTC](https://discourse.laminas.dev/t/simple-example-of-di-autowiring-in-laminas-mvc/3291 "2023-04-14T17:55:00Z")\
**Posts on this page:** 9\
**Page:** 1

<div class="post-metadata">

**Author:** ![stark](https://yyz2.discourse-cdn.com/flex032/user_avatar/discourse.laminas.dev/stark/32/535_2.png) [@stark](https://discourse.laminas.dev/u/stark)\
**Post date:** [April 14, 2023, 5:55pm UTC](https://discourse.laminas.dev/t/simple-example-of-di-autowiring-in-laminas-mvc/3291/1 "2023-04-14T17:55:00Z")

</div>

Hey guys,

I am reading in the docs that Laminas-DI supports autowiring out of the box. So if understand that correctly, I should not need any configuration and classes should be injected via contructors right away. However that is not the case 🙂  
Are my expectations correct?  
In other frameworks like Laravel or Symfony, if I create a new class and I pass it to a constructor of another class it just gets injected. Does it work the same in Laminas?  
Can you point me to some minimal example? I have already tried but most of the examples I find are either explicitly defining the dependencies or are using an abstract factory concept.

In another words I would like to get rid of the following code in my Module.php 🙂

```auto
public function getControllerConfig(): array
    {
        return [
            'factories' => [
                Controller\AdvertController::class => function($container) {
                    return new Controller\AdvertController(
                        $container->get(Model\AdvertTable::class)
                    );
                },
            ],
        ];
    }

    public function getServiceConfig(): array
    {
        return [
            'factories' => [
                Model\AdvertTable::class => function($container) {
                    $dbAdapter = $container->get(AdapterInterface::class);
                    $resultSetPrototype = new ResultSet();
                    $resultSetPrototype->setArrayObjectPrototype(new Model\Advert());
                    $tableGateway = new TableGateway('advert', $dbAdapter, null, $resultSetPrototype);
                    return new Model\AdvertTable($tableGateway);
                }
            ],
        ];
    }

```

I am kind of evaluating Laminas/Mezzio (among other frameworks) as a candidate to rewrite a ZF1 application but my daily bread is C# or .NET so I know concepts like DI but have not really used them in PHP or Laminas so I might be missing something really elementary.

Thanks a lot

---

<div class="post-metadata">

**Author:** ![froschdesign](https://yyz2.discourse-cdn.com/flex032/user_avatar/discourse.laminas.dev/froschdesign/32/38_2.png) [@froschdesign](https://discourse.laminas.dev/u/froschdesign)\
**Post date:** [April 19, 2023, 7:56am UTC](https://discourse.laminas.dev/t/simple-example-of-di-autowiring-in-laminas-mvc/3291/3 "2023-04-19T07:56:31Z")

</div>

Hello and welcome to our forums! 😃

> [@stark](#):
>
> I am reading in the docs that Laminas-DI supports autowiring out of the box.

If I follow your code examples, you don’t need laminas-di.

> [@stark](#):
>
> In other frameworks like Laravel or Symfony, if I create a new class and I pass it to a constructor of another class it just gets injected. Does it work the same in Laminas?

Sure, use the [reflection-based factory of laminas-servicemanager](https://docs.laminas.dev/laminas-servicemanager/reflection-abstract-factory/) which is already present in a laminas-mvc application. For your controller example this means:

```php
return [
    'factories' => [
        Controller\AdvertController::class => \Laminas\ServiceManager\AbstractFactory\ReflectionBasedAbstractFactory::class,
    ],
];

```

The second example contains some more preparation therefore a separate factory class is recommended here. Then the configuration can also be cached.

You can find more examples of the usage of the reflection-based factory in the tutorials:

> **[tutorials - Laminas Docs](https://docs.laminas.dev/tutorials/#application-integrations)**
>
> Learn how to create laminas-mvc applications, get in-depth guides into components, and discover how to migrate your applications to version 3!

> [@stark](#):
>
> I am kind of evaluating Laminas/Mezzio (among other frameworks) as a candidate to rewrite a ZF1 application…

Then Mezzio is the right candidate, because it has a low entry and can handle the migration from ZF1. See:

> [@Migration de Zf 1.11 vers laminas](https://discourse.laminas.dev/t/migration-de-zf-1-11-vers-laminas/2142/5):
>
> Correct, there is no automated migration via script or something else. Some approaches and concepts are too different between version 1 and version 2 of ZF. The topic “dependency injection”, for example, is missing in ZF1. Also the old registry implemented via singleton pattern with global state. These are all old habits and bad practices that have been cut off. My advice for old ZF1 application is to find a way for a soft migration. This means, for example, to clean up all controllers, create…

---

<div class="post-metadata">

**Author:** ![stark](https://yyz2.discourse-cdn.com/flex032/user_avatar/discourse.laminas.dev/stark/32/535_2.png) [@stark](https://discourse.laminas.dev/u/stark)\
**Post date:** [April 19, 2023, 6:32pm UTC](https://discourse.laminas.dev/t/simple-example-of-di-autowiring-in-laminas-mvc/3291/4 "2023-04-19T18:32:08Z")

</div>

Hey @froschdesign,

thanks a lot for your input.

So if I am correct even if I use the reflection-based factory I need to explicitly configure it for every single class or can I make the reflection-based factory a default or something like that to achieve the behavior of other frameworks where it just works out of the box?

Sure, I understand that in cases like the second example (the one with more preparation) the specific factory makes sense and is the only reasonable option. But I actually don’t like the code of the second example I just put it here since it is present in the docs. I mean imagine having more tables in DB (which is quite an expected scenario I would say) it does not make much sense to me to have such a complicated factory for each model/table gateway like that. I would definitively look for another option in this case.

Yeah, I have googled a lot and Mezzio seems to be quite a good choice to migrate from ZF1 using the strangler pattern. But to be honest since migration from ZF1 means a sort of complete rewrite anyway that puts other (non Laminas) frameworks into play to. And I must say I am kind of twisted here. I mean I like the idea of having everything under my control in Laminas/Mezzio as opposed to other “magical” frameworks. On the other hand I also see the benefit there as one do not have to define everything as it gets tedious and repetitive.

I hope I was able to express myself in a way that is understandable and clear. Thanks again for your response. I will probably spend some more time evaluating 🙂

---

<div class="post-metadata">

**Author:** ![froschdesign](https://yyz2.discourse-cdn.com/flex032/user_avatar/discourse.laminas.dev/froschdesign/32/38_2.png) [@froschdesign](https://discourse.laminas.dev/u/froschdesign)\
**Post date:** [April 19, 2023, 6:38pm UTC](https://discourse.laminas.dev/t/simple-example-of-di-autowiring-in-laminas-mvc/3291/5 "2023-04-19T18:38:36Z")

</div>

> [@stark](#):
>
> …can I make the reflection-based factory a default…

Of course you can, register it as an [abstract factory](https://docs.laminas.dev/laminas-servicemanager/configuring-the-service-manager/#abstract-factories):

```auto
use Laminas\ServiceManager\AbstractFactory\ReflectionBasedAbstractFactory;

return [
    'service_manager' => [
        'abstract_factories' => [
            ReflectionBasedAbstractFactory::class,
        ],
    ],
    // …
];

```

Another option is to use a [CLI command](https://docs.laminas.dev/laminas-servicemanager/console-tools/#generate-factory-for-class) to create a factory. Is also better for the performance.  
(Version 4 of laminas-servicemanager will bring more).

> [@stark](#):
>
> But in case I would have more tables in DB it does not make much sense to me to have such a complicated factory for each model/table gateway like that. I would definitively look for another option in this case.

It is quite simple: do not use laminas-db. 😄  
I don’t use it either, it’s too complicated.

---

<div class="post-metadata">

**Author:** ![froschdesign](https://yyz2.discourse-cdn.com/flex032/user_avatar/discourse.laminas.dev/froschdesign/32/38_2.png) [@froschdesign](https://discourse.laminas.dev/u/froschdesign)\
**Post date:** [April 19, 2023, 6:46pm UTC](https://discourse.laminas.dev/t/simple-example-of-di-autowiring-in-laminas-mvc/3291/6 "2023-04-19T18:46:01Z")

</div>

I can recommend the following library if you are interested in autowiring for Laminas and Mezzio:

> **[GitHub - reinfi/zf-dependency-injection: Advanced dependency injection for...](https://github.com/reinfi/zf-dependency-injection)**
>
> Advanced dependency injection for laminas framework - GitHub - reinfi/zf-dependency-injection: Advanced dependency injection for laminas framework

---

<div class="post-metadata">

**Author:** ![stark](https://yyz2.discourse-cdn.com/flex032/user_avatar/discourse.laminas.dev/stark/32/535_2.png) [@stark](https://discourse.laminas.dev/u/stark)\
**Post date:** [April 23, 2023, 6:28pm UTC](https://discourse.laminas.dev/t/simple-example-of-di-autowiring-in-laminas-mvc/3291/7 "2023-04-23T18:28:29Z")

</div>

Thanks a lot. It always takes some time to understand the philosophy behind the framework 🙂

Btw I am probably weird but I do not like Doctrine either. What I really like is the good old Zend\_Db\_Select stuff enhanced with hydrators to get typed objects instead of arrays.

---

<div class="post-metadata">

**Author:** ![stark](https://yyz2.discourse-cdn.com/flex032/user_avatar/discourse.laminas.dev/stark/32/535_2.png) [@stark](https://discourse.laminas.dev/u/stark)\
**Post date:** [April 23, 2023, 6:29pm UTC](https://discourse.laminas.dev/t/simple-example-of-di-autowiring-in-laminas-mvc/3291/8 "2023-04-23T18:29:03Z")

</div>

Thanks for the library tip, that looks interesting.

---

<div class="post-metadata">

**Author:** ![froschdesign](https://yyz2.discourse-cdn.com/flex032/user_avatar/discourse.laminas.dev/froschdesign/32/38_2.png) [@froschdesign](https://discourse.laminas.dev/u/froschdesign)\
**Post date:** [April 24, 2023, 7:27am UTC](https://discourse.laminas.dev/t/simple-example-of-di-autowiring-in-laminas-mvc/3291/9 "2023-04-24T07:27:04Z")

</div>

> [@stark](#):
>
> What I really like is the good old Zend\_Db\_Select stuff enhanced with hydrators to get typed objects instead of arrays.

The same works with laminas-db:

> **[Result Sets - laminas-db - Laminas Docs](https://docs.laminas.dev/laminas-db/result-set/)**
>
> Database abstraction layer, SQL abstraction, result set abstraction, and RowDataGateway and TableDataGateway implementations

But why use a library that does not support relationships? 🤷🏻‍♂️

---

<div class="post-metadata">

**Author:** ![stark](https://yyz2.discourse-cdn.com/flex032/user_avatar/discourse.laminas.dev/stark/32/535_2.png) [@stark](https://discourse.laminas.dev/u/stark)\
**Post date:** [April 24, 2023, 7:43am UTC](https://discourse.laminas.dev/t/simple-example-of-di-autowiring-in-laminas-mvc/3291/10 "2023-04-24T07:43:25Z")

</div>

> But why use a library that does not support relationships? 🤷🏻‍♂️

That would be another discussion 🙂
