Skip to content

Request for feature: Service layer #66

@archlicher

Description

@archlicher

I have struggled with unit testing controllers. In my personal opinion, AspectMock is pretty tricky and takes much time to be configured. I need something quick, easy to extend, showing results asap, especially when I need to test data with logged user.
Yet, controllers, as they are supposed to, return (in most cases) html with response status, rather than simple data or anything testable - not that they are not important, but I find that this is also tested during development, so it may be left out in the unit testing.
Still I need to test the data I get from the models.
I have some experience with ASP.NET and Java EE, where it is considered good practice to separate the (so called) business logic from the controller and model in another layer - Service Layer. This way the work is done as follows:

  1. the controller receives request and returns responses. When data is needed, it requests it from the service
  2. the service basically implements all the business logic and manipulates/modifies data accordingly
  3. the model represents the table from the db

Personally I find it simpler to keep the validation of input fields in the controller, rather than move it to the service. The service should only modify, no need to validate inputs.

Please do check the sample code I have uploaded at my https://github.com/archlicher/fuelphp_req_4_feat. For brevity I have uploaded only the controller and the service, as they are the only piece of software that I have changed. (Notice! if you are to try it with your own project, don't forget to add the Service namespace and classes to your config and bootstrap files).

Finally I wish to point out a few pros:

  1. testing is much easier - especially with logged user - as I need to pass the user to the service action.
  2. the controller is much shorter, easier to follow, maintainable and expandable. The same goes for the service, but in additionally calling the service from another controller/service is much clear and easier.
  3. less coupling, higher cohesion

As it is quite simple and I must have surely missed out some pivotal points, way will not be the best, still I do believe there are reasons to put some thought in to it.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions