Application Service Level - How to write APIs

How do people create their service level interfaces?

I program a large web application (in PHP), and we use MVC and program thin controllers, for example. (pseudo code follows)

public savePersonAction() { $input = filter($_GET); ... input validation ... $result = $this->_service->savePerson( ? ); ... etc } 

Should savePerson in a service accept an argument to the entire structure or input context of $ (in PHP, an associative array)?

eg. this is -

 public function savePerson(array $input) { 

or you should select all input fields and provide a "hard" interface, for example.

 public function savePerson($title, $firstName, $lastName, $dateOfBirth, ... etc.. for many more) { 

Thanks.

Floor

+6
php web-applications model-view-controller service service-layer
source share
3 answers

If you intend to follow the spirit of MVC, your savePerson method savePerson not accept the original input. It should not be directly related to the format of the data coming from ui. Instead, it should accept input defined in terms of your service domain, for example, a person object. (It could just be an associative array, as Kobby suggested). It would be the task of the controller action method to match the raw input in the format required by the service.

The advantage of this additional translation step is that it isolates your service (model) from ui. If you implement a different ui, you do not need to change the service interface. You just need to write new controllers (and views, of course).

While your example, for example savePerson($title, $firstName, $lastName...) , is the right idea, it is usually a bad sign when you have methods with more than two or three arguments. You must group related arguments into some kind of higher-level object.

+5
source share

My MVC applications are structured as follows: Controller -> Service -> ORM / other library

To answer your question, as a rule, in your controller you will receive form data as an array, i.e. $ form-> getValues ​​() or something like that. From the point of view of maintainability, it is best if your Services, except for arrays, as arguments, so if you add another field to the form, you only need to update the form and service, your controller can remain intact and still work.

So, I think we get down to your first example:

 public function savePerson($personArray); 

In addition, you do not need a β€œhard” interface because your form library will take care of validation / filtering / sanitation, so we can assume that the associative array will be valid, plus the method definition will be ridiculously long with the name parameters.

+1
source share

I would select all input fields and provide a "hard" interface in Service, for example.

 public function savePerson($title, $firstName, $lastName, $dateOfBirth) {...} 

Cleaner and there are no assumptions.

0
source share

All Articles