Does it make sense to use PHP setters only for type safety?

I have a group of domain objects, and I use overloading to get and set properties.

My form filters are comprehensive. If properties of the wrong type or value are stolen, I'm sure I can pick them up in the mapper. In the worst case scenario, the database is throwing an exception that I can catch.

In this case, should you worry about getters and setters in the domain object?

+4
source share
3 answers

As a best practice, you should always “catch what you can” before you enter the database. Although it may seem that a round trip is not important, they are expensive. Objects must be created on the server, managed by application pool resources, and more. Perform all the checks, although this is tedious before you get into the database.

The reason you rely on the database to throw exceptions is to ensure its integrity through other forms of access (e.g. import scripts) rather than using it for your application (which is able to catch and process them gracefully).

The ultimate advantage of constructing get and set operations is that you can completely encapsulate these border checks, so you only need to write code once, you go in the right direction!

+1
source

Well, in my opinion, there is no good answer.

If you do this, you can be 100% certain that the return value is of type x. Otherwise, you will depend on the data level for the correct material.

I check the values, but this is mainly because I like defensive programming (anything that goes beyond malicious and should not be trusted). The domain object is beyond the scope of the display device, so you do not know what you are getting.

Next, if you make an api of some type and reuse domain objects out of scope, check the values.

The conclusion depends on the style of code that you like. This way you can implement getters and settings, or just go to the values.

Although I recommend using at least getters and setters for the case, you need to change how the handeld values ​​are (for example, the array should become an object)

0
source

Defining explicit "getters and setters" will allow you to implement the right encapsulation for your domain model.

From a tuning perspective, this will be type checking for complex values. Then you can perform any validation that is applicable in the context of the domain model.

When the domain model is saved, this “check” really ensures that the values ​​are stored correctly. The only thing that a cartographer can have is to transfer simple (scalar) values ​​to the correct format (for example, dates, etc.). These operations are usually database specific and are likely to be better fitted in the mapper.

0
source

Source: https://habr.com/ru/post/1484189/


All Articles