# Folder structure for Expressive modules

**URL:** <https://discourse.laminas.dev/t/folder-structure-for-expressive-modules/153>\
**Category:** Mezzio\
**Tags:** expressive\
**Created:** [June 7, 2017, 10:27am UTC](https://discourse.laminas.dev/t/folder-structure-for-expressive-modules/153 "2017-06-07T10:27:17Z")\
**Posts on this page:** 18\
**Page:** 1

<div class="post-metadata">

**Author:** ![enrico](https://yyz2.discourse-cdn.com/flex032/user_avatar/discourse.laminas.dev/enrico/32/12_2.png) [@enrico](https://discourse.laminas.dev/u/enrico)\
**Post date:** [June 7, 2017, 10:27am UTC](https://discourse.laminas.dev/t/folder-structure-for-expressive-modules/153/1 "2017-06-07T10:27:17Z")

</div>

I would like to open a discussion about a possible folder structure for an Expressive module.  
I’m working with some prototypes and I’ve got some different ideas. The goal is to design a simple folder structure that is reusable, general purpose, and can facilitate people to start working, without wondering where to put code.

At the moment, I’m using something like this:

/src/Foo  
/src/Foo/config  
/src/Foo/src  
/src/Foo/templates  
/src/Foo/ConfigProvider.php

where `Foo` is the name of the module under the `/src` folder. The module configuration is stored in the `config` folder (consumed by `ConfigProvider.php`). The source code of the module is stored in `src` folder. If present, the templates are stored in a `template` folder.

The source code of the module is stored in the `Foo/src` folder with the following sub-dirs:

/src/Foo/src/Middleware  
/src/Foo/src/Action  
/src/Foo/src/Service

The middleware classes are stored in `Middleware` or `Action` folder, depending if the class delegates processing in one or more paths through its logic (`Middlware`) or the class _never_ delegate processing, but _always_ generate and return a response on their own (`Action`). Typically, a _routed_ middleware is stored in Action, and pretty much everything else in Middleware.

The `Service` folder contains classes related to the business logic (like a model) or classes that facilitate the business logic. These classes are stored in a service container (PSR-11).

Thoughts?

---

<div class="post-metadata">

**Author:** ![moderndeveloperllc](https://yyz2.discourse-cdn.com/flex032/user_avatar/discourse.laminas.dev/moderndeveloperllc/32/79_2.png) [@moderndeveloperllc](https://discourse.laminas.dev/u/moderndeveloperllc)\
**Post date:** [June 7, 2017, 1:38pm UTC](https://discourse.laminas.dev/t/folder-structure-for-expressive-modules/153/2 "2017-06-07T13:38:58Z")

</div>

I guess the intent is to emulate a ZF3 module structure? Sounds about right. I have a `src` folder that is very similar. The only suggestion would be to not have something simply titled “Middleware” as the classes in `Action` are middleware too. I went with `PipedMiddleware`, `RoutableAction`, `Service`, but in retrospect that could still be a touch confusing. Perhaps something like:

```auto
PipedMiddleware
RoutedMiddleware

```

would be a little more explicit without having to be explained in documentation.

Having what amounts to nested `/src` directories seems a touch redundant and might make the namespacing more difficult to follow. Do we really need the `Foo` folder? Most PSR-4 compliant packages would just have the `PipedMiddleware`, `RoutedMiddleware`, and `Service` folders at the top level `/src` folder for a structure like:

```auto
composer.json
/config
/src
---/src/ConfigProvider.php
---/src/PipedMiddleware
---/src/RoutedMiddleware
---/src/Service
/templates
/tests

```

This keeps the `src` folder limited to namespaced classes that can be called in the application.

(Edited: Added a cleaned up structure idea)

---

<div class="post-metadata">

**Author:** ![enrico](https://yyz2.discourse-cdn.com/flex032/user_avatar/discourse.laminas.dev/enrico/32/12_2.png) [@enrico](https://discourse.laminas.dev/u/enrico)\
**Post date:** [June 7, 2017, 3:43pm UTC](https://discourse.laminas.dev/t/folder-structure-for-expressive-modules/153/3 "2017-06-07T15:43:50Z")

</div>

@moderndeveloperllc yes, the idea is to provide a common way to design reusable module against different Expressive projects, like we have in ZF2/3 with MVC.

I like your idea to simplify the namespaces. In case of a module as external vendor you right, we omit the Foo folder, but if we have modules in the same Expressive skeleton we need to use a name (and a folder).

I also like the idea to use only suffix for specific `src` classes, like `src/RoutedMiddleware`. My only concern is about some module that contains a lot of actions, middleware and services. Maybe this should be a good signal to split it in seperate modules?

---

<div class="post-metadata">

**Author:** ![moderndeveloperllc](https://yyz2.discourse-cdn.com/flex032/user_avatar/discourse.laminas.dev/moderndeveloperllc/32/79_2.png) [@moderndeveloperllc](https://discourse.laminas.dev/u/moderndeveloperllc)\
**Post date:** [June 7, 2017, 4:09pm UTC](https://discourse.laminas.dev/t/folder-structure-for-expressive-modules/153/4 "2017-06-07T16:09:06Z")

</div>

I had been thinking of third-party modules when suggesting to remove `Foo`. I’m currently refactoring some API middleware and services out of a project so I can reuse it elsewhere.

Sorry, I realized I might not have been the most specific about `PipedMiddleware` and `RoutedMiddleware`. I was suggesting that they were folders that could contain however many classes inside. I guess having lots or few middleware is up to the dev. Some of us are “lumpers” and some “splitters”. For instance, I have

```auto
PipedMiddleware/
  AuthenticationFactory.php
  AuthenticationMiddleware.php
  AuthorizationFactory.php
  AuthorizationMiddleware.php
  Helper/
    LoggingSetUserMiddleware.php
    QueryAttributeParamsMiddleware.php
  LoggingFactory.php
  LoggingMiddleware.php
  RouteNotFoundHandler.php

```

I kept my factories in the same namespace because there were so few. I know many would create a `Factory` directory for those.

---

<div class="post-metadata">

**Author:** ![Xeras](https://avatars.discourse-cdn.com/v4/letter/x/9dc877/32.png) [@Xeras](https://discourse.laminas.dev/u/Xeras)\
**Post date:** [June 8, 2017, 12:22pm UTC](https://discourse.laminas.dev/t/folder-structure-for-expressive-modules/153/5 "2017-06-08T12:22:28Z")

</div>

I think the first “/src” directory is the module root. All other directories inside “/src/Foo/src” are PSR-4 compliant.

To avoid such a missunstanding the directory structure should look like this:

/project\_root  
—/module  
------/Foo  
---------/src  
------------/ConfigProvider.php  
------------/PipedMiddleware  
---------------/Service  
------------------/AuthenticationFactory.php  
---------------/AuthenticationMiddleware.php  
------------/RoutedMiddleware  
---------------/Service  
------------------/MyRoutedMiddlewareFactory.php  
---------------/MyRoutedMiddleware.php  
------------/Service  
------/Bar  
---------/src  
------------/ConfigProvider.php  
------------/PipedMiddleware  
------------/RoutedMiddleware  
------------/Service

Additionally i would suggest to put all factories inside a separate directories to avaoid cluttering than a module have many factories.

---

<div class="post-metadata">

**Author:** ![matthew](https://yyz2.discourse-cdn.com/flex032/user_avatar/discourse.laminas.dev/matthew/32/14_2.png) [@matthew](https://discourse.laminas.dev/u/matthew)\
**Post date:** [June 8, 2017, 1:48pm UTC](https://discourse.laminas.dev/t/folder-structure-for-expressive-modules/153/6 "2017-06-08T13:48:31Z")

</div>

> [@Xeras](#):
>
> Additionally i would suggest to put all factories inside a separate directories to avaoid cluttering than a module have many factories.

I personally dislike this practice, for two reasons:

- It makes discovery of the factories more difficult. Where do I look — in a `Factory` directory under the current one? in a `Service` directory under the current one? Or are those up a level, i.e., in a peer namespace? If so, they then might contain factories for multiple namespaces, which can also be confusing.
- It makes writing the factories harder. When the class the factory creates is in the same namespace, you don’t need to import it. When it’s in a sibling namespace, you need to import it. When it’s in a subnamespace, you have redundant information in the class name: `Factory\SomeMiddlewareFactory` or `Service\SomeMiddlewareFactory`.

Which brings me to a couple more notes.

First, in your example, you have things like the following:

```auto
|-- AuthenticationMiddleware.php
|-- Service
    |-- AuthenticationFactory.php

```

This is confusing, as it’s unclear from the name whether `AuthenticationFactory` will create an instance of the `AuthenticationMiddleware`, or some nebulous `Authentication` class. The factories should clearly indicate _what_ they create.

Second, the name `Service` is nebulous, particularly for somebody not familiar with Zend Framework in particular. Does it refer to something accessing a _web service_? Or is it something that provides a particular web service? or is it some other type of service entirely? To answer the question, it’s the latter. In your example, it’s referring to a “service” registered in a “service manager”, which is what ZF calls its dependency injection container. In Enrico’s original post, it’s actually referring to domain models and similar.

If we consider your example, where the `Service` directory and subnamespace is for seeding the DI container, if we consider the fact that Expressive is a PSR-11 consumer, which defines a `ContainerInterface`, and the classes in these directories provide _factories_ by which the container can retrieve dependencies, `Factory` is a more clear namespace _if you really, really need to separate such classes_. As noted earlier, I think it’s far better to keep them together in the same namespace.

In Enrico’s example, I’d argue that the directory/namespace should be `Model` or `Domain`, _if it needs to exist at all_. Many of these classes are often the core of a module. As a quick example, let’s say I’ve created a module for a web service that will list books in an inventory, and allow manipulating the inventory. My basic entities might be a `Book` class, a `Collection` (for sets of books), a `Repository` (for retrieving books from my persistent storage), and an `InputFilter` (for validating new and/or updated book entries submitted to the service). These could be in the _root_ of the module. I might then have a `Middleware` subdirectory/subnamespace that contains the various middleware for the web service itself, and which uses these classes:

```auto
Books
|-- src
    |-- Book.php
    |-- Collection.php
    |-- ConfigProvider.php
    |-- InputFilter.php
    |-- Repository.php
    |-- Middleware
        |-- AddBookMiddleware.php
        |-- BookMiddleware.php
        |-- SearchMiddleware.php
        |-- UpdateBookMiddleware.php
|-- templates
|-- test

```

All that said, though, I think what Enrico is trying to get at is having a _suggested_, _recommended_ directory structure for modules that is _predictable_. This makes it easier for developers working on an existing module for the first time to understand the structure: they know where to find classes that provide specific areas of functionality, and where to put new classes, based on their functionality. Additionally, it allows us to have our tooling that creates modules create these standard subdirectories, eliminating the need for developers to create their own structure. If this is what we want to provide, then a `Domain` or `Model` subnamespace would make sense.

Of course, any of these subnamespaces may be omitted _if the module does not provide classes that fill those roles_.

Finally, I’ll throw this out there, as it’s a discussion I’ve had with @enrico and others a few times the past month:

> The term **middleware** should refer to any middleware that _delegates processing of the request_ in one or more branches of its logic. The terms **action** or **handler** should refer to middleware _that never delegates processing_, and, instead, _always generates and returns a response on its own_.

With that in mind, we’d have `Middleware` and/or `Action` (or `Handler`) subnamespaces, depending on what functionality the module exposes.

---

<div class="post-metadata">

**Author:** ![Xeras](https://avatars.discourse-cdn.com/v4/letter/x/9dc877/32.png) [@Xeras](https://discourse.laminas.dev/u/Xeras)\
**Post date:** [June 8, 2017, 2:34pm UTC](https://discourse.laminas.dev/t/folder-structure-for-expressive-modules/153/7 "2017-06-08T14:34:50Z")

</div>

Thank you for this interessting ponts. The class name “AuthenticationFactory” was just a misspelling, sorry for confusion, I totally agree with you.

What is you optinon to “/module” vs “/src” as the name of the module root directory?

---

<div class="post-metadata">

**Author:** ![matthew](https://yyz2.discourse-cdn.com/flex032/user_avatar/discourse.laminas.dev/matthew/32/14_2.png) [@matthew](https://discourse.laminas.dev/u/matthew)\
**Post date:** [June 8, 2017, 2:58pm UTC](https://discourse.laminas.dev/t/folder-structure-for-expressive-modules/153/8 "2017-06-08T14:58:29Z")

</div>

> [@Xeras](#):
>
> What is you optinon to “/module” vs “/src” as the name of the module root directory?

I prefer `src/`, as it allows either modules _or_ libraries, thus keeping all _source code_ for the application in one place.

---

<div class="post-metadata">

**Author:** ![tasmaniski](https://yyz2.discourse-cdn.com/flex032/user_avatar/discourse.laminas.dev/tasmaniski/32/70_2.png) [@tasmaniski](https://discourse.laminas.dev/u/tasmaniski)\
**Post date:** [June 10, 2017, 8:23pm UTC](https://discourse.laminas.dev/t/folder-structure-for-expressive-modules/153/9 "2017-06-10T20:23:22Z")

</div>

I created a very similar structure as Enrico show with little modifications.  
@enrico are you sure about /src/Foo/ConfigProvider.php shouldn’t that be /src/Foo/src/ConfigProvider.php ?

1. First of all I prefer to name top level dir “packages” since “src” is little bit confusing for me.

2. In small package I will put big array in ConfigProvider.php and return it.  
If package is a bigger separated configs would be better.

3. Also I prefer to hold all Factories in the same dir where classes are.  
But sometimes if package grow for eg. 70 separated Actions (that would be 140 files with factories)  
it is little bit easier to brows the files if they are in separate folders like

4. I like the idea to hold all domain classes in src dir like matthew show,  
but don’t know how that would look in just a little bigger package/module…

This would be one typical module/package from my app

```
├── Page
    ├── src
    │ ├── ConfigProvider.php
    │ ├── Action
    │ │ ├── IndexActionFactory.php
    │ │ └── IndexAction.php
    │ ├── Entity
    │ │ └── Page.php
    │ ├── Filter
    │ │ └── PageFilter.php
    │ ├── Mapper
    │ │ ├── PageMapperFactory.php
    │ │ └── PageMapper.php
    | ├── Middleware
    │ └── Service
    │ ├── PageServiceFactory.php
    │ └── PageService.php
    ├── test
    └── templates
        ├── page
        │ └── index.phtml
        └── partial
            └── pagination.php

```

I guess it’s all depend from one question “How big is package/module?”.

It’s a really god topic! Thanks Enrico.

---

<div class="post-metadata">

**Author:** ![RalfEggert](https://yyz2.discourse-cdn.com/flex032/user_avatar/discourse.laminas.dev/ralfeggert/32/76_2.png) [@RalfEggert](https://discourse.laminas.dev/u/RalfEggert)\
**Post date:** [June 11, 2017, 7:14pm UTC](https://discourse.laminas.dev/t/folder-structure-for-expressive-modules/153/10 "2017-06-11T19:14:01Z")

</div>

Very interesting and important topic!

First, I also do not like to top `/src/` folder as well. Whenever I use the skeleton installer, the very first thing I do is to rename it to `/module/`. I know that all files in a module are somehow source code (templates, config files, classes). But the duplication of `/src/` in the same pass just doesn’t feel right. I had the same discussion with @matthew a while ago without a result. There are different opinions.

Anyway I really do not like a folder named `/service/`. It always raises the question: What is a service? If you are doing the DDD approach it is well defined, but a lot of programmers just name their classes `WhateverService` if they have no proper name. I really like the layer approach with the following subdirs:

- `/module/Foo/src/Application/` for actions and other application services
- `/module/Foo/src/Domain/` for all domain classes like entities, repositories, storages, input filters and domain services
- `/module/Foo/src/Infrastructure/` for all infrastructure stuff like table gateway classes and infrastructure services like emailing, logging and stuff
- `/module/Foo/src/Presentation/` for forms, view helper or other presentation classes

Not every module has all of these subdirs but every subdir is divided again.

So my point here is it will be very hard to find a good recommendation for the `/src/` subdir folder. I would always only set some common rules like place factory in the same folder than the class it creates and stuff like that.

Thanks, Ralf

---

<div class="post-metadata">

**Author:** ![ocramius](https://yyz2.discourse-cdn.com/flex032/user_avatar/discourse.laminas.dev/ocramius/32/23_2.png) [@ocramius](https://discourse.laminas.dev/u/ocramius)\
**Post date:** [June 11, 2017, 7:34pm UTC](https://discourse.laminas.dev/t/folder-structure-for-expressive-modules/153/11 "2017-06-11T19:34:17Z")

</div>

This is kinda controversial though: all modules are sources, not all  
sources are modules 😉

I currently don’t even use modules anymore: just put everything under  
`config/autoload.php`.

Marco Pivetta

[http://twitter.com/Ocramius](http://twitter.com/Ocramius)

[http://ocramius.github.com/](http://ocramius.github.com/)

---

<div class="post-metadata">

**Author:** ![RalfEggert](https://yyz2.discourse-cdn.com/flex032/user_avatar/discourse.laminas.dev/ralfeggert/32/76_2.png) [@RalfEggert](https://discourse.laminas.dev/u/RalfEggert)\
**Post date:** [June 11, 2017, 7:48pm UTC](https://discourse.laminas.dev/t/folder-structure-for-expressive-modules/153/12 "2017-06-11T19:48:24Z")

</div>

Put your sources that are not a module in the `/src/` folder and the sources that are a module in a `/module/` folder. Problem fixed 😉

---

<div class="post-metadata">

**Author:** ![harikt](https://yyz2.discourse-cdn.com/flex032/user_avatar/discourse.laminas.dev/harikt/32/47_2.png) [@harikt](https://discourse.laminas.dev/u/harikt)\
**Post date:** [June 15, 2017, 6:13pm UTC](https://discourse.laminas.dev/t/folder-structure-for-expressive-modules/153/13 "2017-06-15T18:13:50Z")

</div>

Hi all,

I like the proposal of brain storming the modules. When I hear the term module, I always think about re-usability. So a module should be

1 ) Re-usable  
2 ) Flexibile enough to change templates / assets  
3 ) Easy to configure

I have been thinking about this idea for sometime. And tried to come up with some prototype. My idea was not just for expressive but for any PSR-7, PSR-15, PSR-17 frameworks.

Probably some of you may have came across the post : [http://harikt.com/blog/2017/03/24/building-modular-applications-with-psr-7/](http://harikt.com/blog/2017/03/24/building-modular-applications-with-psr-7/)

The structure of the module was as

```
src
    Container
    Middleware
    ConfigProvider.php
templates
   action1.twig
   // or
   action2.php
public
    css
    images
    js

```

What I actually struggled was there was no way in ConfigProvider.php to load an object from di container and modify something on the particular service.

You may not be sure why I want to do the same, and probably @ocramius would say that is actually a bad idea changing the state 😉 .

What I was trying to do was get the `AssetLocator` and set the path where the assets resides for each module.

> <https://github.com/harikt/psr7-asset-example/blob/89c3e2fd66a9ced9d325939a562db503c1197422/src/Container/Common.php#L21-L22>

And once all `ConfigProviders` are merged you can alter where the application specific asset paths.

> <https://github.com/harikt/psr7-asset-example-zendexpressive/blob/d1aa8732d83dca70f0c851f88149b3a02791ba8e/src/App/Config/Common.php#L44-L46>

The assets are actually served by a separate library : [https://github.com/harikt/psr7-asset](https://github.com/harikt/psr7-asset) which is actually a fork of [https://github.com/friendsofaura/Aura.Asset\_Bundle](https://github.com/friendsofaura/Aura.Asset_Bundle) .

You can see a complete example on expressive : [https://github.com/harikt/psr7-asset-example-zendexpressive](https://github.com/harikt/psr7-asset-example-zendexpressive)

As I mentioned if you created a module `user` then it is possible to change the `js` , `css`, `images` and with the help of namespace template with zend-expressive you can alter the template also.

Thank you for your time. If there is anything unclear I am happy to discuss about the same.

---

<div class="post-metadata">

**Author:** ![matthew](https://yyz2.discourse-cdn.com/flex032/user_avatar/discourse.laminas.dev/matthew/32/14_2.png) [@matthew](https://discourse.laminas.dev/u/matthew)\
**Post date:** [June 19, 2017, 1:08pm UTC](https://discourse.laminas.dev/t/folder-structure-for-expressive-modules/153/14 "2017-06-19T13:08:51Z")

</div>

> [@harikt](#):
>
> What I actually struggled was there was no way in ConfigProvider.php to load an object from di container and modify something on the particular service.

We do have a way to do this already: [delegator factories](https://docs.zendframework.com/zend-expressive/features/container/delegator-factories/). These are supported by the v2.X skeleton and later for all supported containers, and allow you to modify or replace a service after initial creation.

Additionally, all `ConfigProvider` classes are merged during bootstrapping of the `config` service, which happens even before a container is created, which fulfills the other requirement you specify.

---

<div class="post-metadata">

**Author:** ![harikt](https://yyz2.discourse-cdn.com/flex032/user_avatar/discourse.laminas.dev/harikt/32/47_2.png) [@harikt](https://discourse.laminas.dev/u/harikt)\
**Post date:** [June 19, 2017, 2:59pm UTC](https://discourse.laminas.dev/t/folder-structure-for-expressive-modules/153/15 "2017-06-19T14:59:55Z")

</div>

Thank you @matthew . I have looked at the delegator factories doc. One thing I am confused is the callback. How can we make sure what is the callback it is receiving. But that looks a separate topic to be discussed.

---

<div class="post-metadata">

**Author:** ![matthew](https://yyz2.discourse-cdn.com/flex032/user_avatar/discourse.laminas.dev/matthew/32/14_2.png) [@matthew](https://discourse.laminas.dev/u/matthew)\
**Post date:** [June 19, 2017, 9:39pm UTC](https://discourse.laminas.dev/t/folder-structure-for-expressive-modules/153/16 "2017-06-19T21:39:24Z")

</div>

> [@harikt](#):
>
> One thing I am confused is the callback. How can we make sure what is the callback it is receiving. But that looks a separate topic to be discussed.

Indeed, but the short answer is: do an `instanceof` check, and if it’s not of a type you recognize, just return it verbatim without operating on it.

---

<div class="post-metadata">

**Author:** ![enrico](https://yyz2.discourse-cdn.com/flex032/user_avatar/discourse.laminas.dev/enrico/32/12_2.png) [@enrico](https://discourse.laminas.dev/u/enrico)\
**Post date:** [June 20, 2017, 3:46pm UTC](https://discourse.laminas.dev/t/folder-structure-for-expressive-modules/153/17 "2017-06-20T15:46:56Z")

</div>

Ok, thanks for the feedback! I think we can summarize the idea and simplify a **Module** structure with the following folders:

- config;
- src;
- templates;

The **src** folder will contain all the source code of the module. Here we can have also subfolder, such as:

- Action (for the routed middleware, returning a response);
- Middleware (for generic middleware, usually consuming $delegate/$next);
- Model (for the business logic).

All the source code can be also stored in **src** without any subfolder. This really depends on the use case and developer’s preference. The class files should be named using a significant suffix, e.g. Action, Middleware, etc.

The only requirement of **src** is that it MUST contain a _ConfigProvider.php_ file to serve the configuration.

The only open question, related with the @harikt reply, it’s the **public** folder. IMHO I think it’s ok, we need to find a “standard” way to serve this folder in the web server, using some asset library/idea.

---

<div class="post-metadata">

**Author:** ![harikt](https://yyz2.discourse-cdn.com/flex032/user_avatar/discourse.laminas.dev/harikt/32/47_2.png) [@harikt](https://discourse.laminas.dev/u/harikt)\
**Post date:** [August 23, 2017, 6:43pm UTC](https://discourse.laminas.dev/t/folder-structure-for-expressive-modules/153/18 "2017-08-23T18:43:22Z")

</div>

Recently I came across a CMS framework : [DMS · GitHub](https://github.com/dms-org/) which made me install laravel for it has some integration for the same.

I noticed a few good things which I liked.

Laravel pushes the templates to a `resources/views/vendor` folder. Now you have all the flexibility to change the views, css, etc for the app. That looks interesting to me. I guess it has some similarities to that of [GitHub - zfcampus/zf-asset-manager: Copy asset files from packages to your public tree during package installation.](https://github.com/zfcampus/zf-asset-manager) .

I may be also wrong for I don’t have a very deep understanding of the laravel eco system. But their way of packing docs look interesting. May be we should borrow some of the good things.

> I have been playing with it to integrate to expressive, but due to limited time wasn’t able to make it work as expected.
