Encapsulation in object oriented PHP - when is it really needed? - php

I know this is kind of a question of faith and has been asked many times before, but the answers I've found were either too general, didn't apply to my use case, or didn't satisfy otherwise.
I'm currently building an application that uses classes as representation for database tables. These classes don't offer any methods of their own, I've written a parser class for each one that works with their objects and returns the data in the format I need, which makes the parent classes nothing more than data storages and makes a nice distinction between data and logic.
Now, the consensus in OOP seems to be that you always have to use getters and setters instead of accessing class attributes directly.
An argument I've often heard is that using getters and setters gives the possibility of extending those functions later on, but in my opinion this goes against YAGNI and some other concepts I can't remember the name of right now - that a method should do exactly what you would expect from its name. If I wanted to do something more than simply set a value, I would write a new method, not put that into my setter method, since that one is, per definition, only supposed to set attributes. So I might as well skip the setter and just access the attribute directly.
Another one is that you can put validation in your setters, which I already do in my API that accesses these classes. In my opinion you shouldn't just pass values and have the object tell you if your value is okay or not, but instead validate those values first before you pass them to the object.
I do understand the purpose of private/protected attributes in "usual" classes, but when the class is literally just a data container without any methods, is this really needed? In other words: is there a glaring disadvantage to using public values, when the setter methods for those (were they private) would all just look like public function getAttr($attr) { $this->atrr = $attr; } anyway?

You only need a data structure, but the only suitable PHP construct is the class.
Typically, in object-oriented analysis, design and programming, a class is a model of a thing or concept and it encapsulates any knowledge and/or behaviour of the thing or concept.
However, in the context of this question, encapsulation is not needed since you only require a data structure.

Related

Are DAO objects better than static DAO classes in PHP?

I understand the reasons for not using statics in Java.
However, I'm currently developing OO code in PHP. I use DAOs with the goal of keeping my queries in one place so I can easily find them. I also instantiate some DAOs so I can incorporate pagination in some (relevant) queries. In many cases, it's not necessary and so I tend to just create static methods (even though technically I don't think I can call that a DAO) in the form:
$info = schemeDAO::someFunction($variable);
I may need only that single method during a page refresh (i.e. a specific value in a header file).
I may need to instantiate the same DAO a hundred times as objects are created and destroyed.
$dao = new myDao();
$info = $dao->someFunction($variable);
Either way, it seems to me, in PHP at least, wouldn't it be more performance efficient to simply load a static and keep it in memory?
While the static access is acceptable (to an extent), with the dynamic approach you can pass the object transitively to the 3rd side object via dependency, (otherwise also the transitive call the transition of dependency would have to be initiated from the original class), which needs not to be pushed some data, but rather the dependency decides and pulls the data/method it needs be it multiple times in a single method. Otherwise way it can only return, while instance can be called, not-separated wrapper method logic from data. Instance inline code seems to be shorter, and when you remove an instance, all their calls complain at that moment, whereas static class continues to preserve unnoticed in the code as they don't need the instantiation prerequisite.
Static classes preserve their state in between various objects, and methods contexts and thus are not automatically "reset" as it is with the 'new construct'. Instances encourage more transparent pure functions approach - passing parameters. When you pass an object, you don't separate the service logic from it's data structure, when you pass only the array data structure, the execution logic is lost in transit or separated into another place and must be eventually called intransparently statically when not-passed - pure functions concept.
I would use comparison with Einsteins vs Newton's equations. In some cases, they look totally the same. But to be pretty content I would use more versatile instances or service locator singletons, vs static classes. On the other side, the less "versatile" static classes might be initially easier to implement, especially if you don't plan on rocket with them as far as to the space orbit as you might get with instances. Similarly as with private attributes you signal they are not passed anywhere, pure functions, though it might less often signalize also the bad, being called from anywhere.

Why does PHP allow calling private methods from other instances?

PHP would let calls to private methods as long as they come from instances of the same class.
This is how the PHP docs explains it:
Objects of the same type will have access to each others private and protected members even though they are not the same instances. This is because the implementation specific details are already known when inside those objects.
Doesn't this break encapsulation? How does the fact that implementation specific details are known justify it?
p.s. Are there other (object oriented) languages that do this?
This is true for most languages, in java you can do it too,
this is because the object is from the same instance, it "knows" all the properties same instances have
As an answer to the post scriptum, Delphi (so-called "object pascal") and Lazarus ("free pascal") both allow access to the private properties only in the same unit that the class implementation is coded. So you can insert two different classes inside one unit and they have access to each other's private properties.
It is not allowed if two classes are placed in different units (let's say it's something like a namespace in PHP).
As an answer to "Doesn't this break encapsulation?":
Although the Encapsulation principle in OOP definition is a bit vague. The way I understand it is it keeps private data and logic in the bounds of a class.
Encapsulation is used to hide the values or state of a structured data object inside a class, preventing unauthorized parties direct access to them.
I don't know if this behaviour of classes in PHP, Java and other languages is good or bad, but I don't think it breaks the Encapsulation of the classes.

How to use one object in another class : PHP framework

This is my current system for a framework that I'm making:
I create an object upon a request to access a non-existing property, that has the name of an existing class through the __get function defined in the Core class. The Core class extends every class.
So it works like this:
class Someclass extends Core
{
public function classmethod()
{
$this->otherclass->method();
}
}
This works exactly how I want it to work. However, I have no idea (after a lot of frustration) how to edit/create properties of the object, using this system.
So something like this would't work.
$this->view->somevar = "newvalue"; // this doesn't work.
I guess it has to do something with the __set function, but I failed to find out.
I received the following suggestions how to tackle this problem:
Dependency injection, Namespaces, Singleton pattern.
I would love to see how to implement what I'm trying to do using one of these patterns.
I have no idea which to choose in order to achieve my simple problem: Use objects in other classes, so i don't need to put anything into __construct's parameters or using global variables.
I am using __autoload.
I hope i can tackle this problem with your help.
First of all, the architecture you're attempting is extremly bad. Aparently you are using "magic" to create objects attached as properties to other objects. Which is bad, because if you use _get/_set, you will end up in problems sooner rather than later. Also extending from a common parent is a bad thing because it generates huge inheritance trees, and it allows most of the objects to have more than one responsability.
Before starting a framework, you might want to look over: SOLID
Now coming back to your question, if you use __get for getting a value, you can as well use __set for setting a value.
__construct method is there in order to allow you to initialize the object with all the data it needs in order to fulfill his sole purpose. Avoiding the __construct is kinda stupid, and defeats the purpose. You might want to pay attention to the D in SOLID in order to see what Dependency Inversion really is and to understand it.
Using __set loses completely the ability to typehint interfaces and so on. Therefore the code can become really buggy and ijcredibly hard to follow, since the flow is not so well defined, and the allocation is done in the back via magic. Also i can come up with 1 million other reason for which the architecture you are trying to use is wrong, but i will leave that for another time.

Why is singleton so bad in a PHP environment? [duplicate]

This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
Who needs singletons?
i was wondering, what are the drawbacks using Singletons in php scripts. I use them alot and i sometimes can't understand criticism of developers. Some examples:
I have a Request class:
Sanitizing POST, GET, COOKIE inputdata and using it instead of the global arrays - strictly and globally. Like
$request = Request::getInstance();
$firstname = $request->post('firstname', $additionalFilters);
There is always only ONE request per request. Why is using singleton in this case a bad idea?
Same for $_SESSION:
I have a Session class (Singleton) which does represent the $_SESSION array because there is only one session and i use it globally.
Database
$mysql = DB::getInstance('mysql', 'dbname'); //pseudo
$sqlite = DB::getInstance('sqlite', 'dbname'); //pseudo
For each type of database, i want only ONE object and never MORE. In my opinion there is otherwise a risk of chaos.
Unique rows
Also i often use classes to represent/use a unique row of a db table.
$article = Article::getInstance($id);
$navigation = Navigation::getInstance($id);
I see only benefits doing it this way. I never want a second object representing a unique row. Why is singleton such a bad idea here?
In fact, most (nearly all) my classes don't have a public constructor but always a static method like getInstance($id) or create() so the class itself handles the possible instances (which doesn't mean they are all singletons by definition)
So my question is: Are there any drawbacks i didn't realize yet. And which concrete scenario's the singleton-doubters thinking of when advise against Singletons.
Edit:
Now, you got a singleton that wraps around the $_POST, but what if you
don't have $_POST, but want to use a file for input instead? In that
case, it would be more convenient if you have an abstract input class,
and instantiate a POSTInput to manage input through posted data.
Ok, valid advantages. I didn't realized that. Especially the point regarding the Request class.
Still i have doubts whether that approach. Assume i have a "Functionality" class which executes a concrete request (like a guestbook component).
Within that class i want to get a sent parameter. So i get my singleton instance of Request
$req = Request::getInstance();
$message = $req->post('message');
This way, only my functionality object cares about a Request class.
When i use the non-singleton approach, i need somehow an additional class/function to manage that every request gets a valid request object. That way my Functionality class doesn't need to know about that managing class but in my opinion there still arises a dependence/problem: Everytime i create an instace of an Functionality object there is a chance that i forget to set a request object.
Surely i can define a non-optional parameter when creating a functionality. But that leads to a parameter overkill altogether at some time. Or not?
Singletons (and static classes, to which the same story largely applies) are not bad per se, but they introduce dependencies that you may not want.
Now, you got a singleton that wraps around the $_POST, but what if you don't have $_POST, but want to use a file for input instead? In that case, it would be more convenient if you have an abstract input class, and instantiate a POSTInput to manage input through posted data.
If you want to get input from a file, or even (for whatever reason) want to mimic (or replay) multiple requests based on input from a database table, you can still do this, without altering any code, except the part that instantiates the class.
Same applies to other classes too. You don't want your whole application to talk to this MySQL singleton.. What if you need to connect to two MySQL databases? What if you need to switch to WhatEverSQL?.. Make abstracts for these kinds of classes, and override them to implement specific technologies.
I do not think singletons should have as bad press they do in a request-based architecture such as PHP or ASP.NET (or whatever you want). Essentially, in a regular program the life-time of that singleton can be as many months or years as the program is running:
int main()
{
while(dont_exit)
{
// do stuff
Singleton& mySingleton = Singleton::getInstance();
// use it
}
return 0;
}
Apart from being little more than a global variable, it is very hard to replace that singleton with, perhaps, a singleton that might be useful in unit-testing. The amount of code that could depend on it, in potentially hundreds of source files tightly couples the use of that singleton to the entire program.
That said, in the case of request-based scenarios such as your PHP page, or an ASP.NET page, all your callable code is effectively wrapped in a function call anyway. Again, they are obfuscating a global variable (but within the context of the request) with safe-guards against being created more than once.
But still, I advocate against their use. Why? Because even in the context of your single request, everything is reliant and tightly coupled to that instance. What happens when you want to test a different scenario with a different request object? Assuming you coded using includes, you now have to go and modify every single instance of that call. If you had passed a reference to a pre-constructed Request class, you can now do cool stuff, such as provide mock unit-testing version of your class, by simply changing what gets passed down to the other functions. You've also de-coupled everything from using this universal Request object.

Is it ok to wind up using mostly static classes?

I'm currently rewriting an e-shop - but only the client side, i.e. the CMS remains mostly in tact. I am not using a pre-built framework, as the system has to retain backwards compatibility with the CMS and I have to have full freedom of the structure of code.
The new system is purely MVC based and I have a Bootstrapper which loads controllers based on the current uri and the latter use models for the real work - both with sessions and the database.
tl;dr It's my first project without a pre-built framework.
I am very inexperienced when it comes to design patterns. I know how do most of the popular ones work but have had never put them to use.
Now I am suspecting code smells because all of my models are classes that consist purely of static methods. I can find no advantages of doing them in a different manner. I routinely need some of the methods in various places through out the code. I.e. I need to fetch the logged in user in the main layout, check user rights to see current page in the bootstraper, display user panel by the controller. I'd need to re-instantiate an object each time or keep a global one if I wasn't using statics. There also won't be a need for more than one such class at a time.
I must be missing something, because even though I use OOP, some my classes are just meaningless containers for their methods (and sometimes a couple of private variables). I could have just been using PHP4 and simple functions.
Any comments or advice would be highly appreciated.
EDIT: in spite of all these educated answers, I remain unconvinced. Even though it's most probably because of my lack of experience, I still don't foresee anything going wrong with the current setup. I mean I don't even fathom a situation where I'd have any inconveniences due to the code architecture as it is now. I hope I don't get a harsh lesson when it's too late to change anything...
You are right, it's a code smell and everybody will tell you it's baaaad.
So here I suggest rather to make a self-assessment of the severity of the problem:
Do you have classes with many getter and setter?
Are your static functions like the one below?
If yes, try to move the logic in the class MyClass that will be already way more OO. That's a classic mistake from procedural/scripting world.
static void myMethod( MyClass anObject )
{
// get value from anObject
// do some business logic
// set value of anObject
}
Do you have a lot of global state, such as data you fetch from the current session?
If yes, make an assessment whether you want to change it. The OO way would be to pass the session down the call chain. But in practice, it's convenient to access the session as a global object. But it impedes testability. Try to remove some global state and turn that into regular object that you pass and manipulate in methods.
Make this assessment, and try to identify utility classes, services classes and the business objects. Utility class are helper classes with utility methods (e.g. formatting, conversion, etc.) which can be static. Service class do some business logic but they should be stateless and one instance suffice. Business objects are user, products, article, etc. is where you must concentrate your effort. Try to turn plain data into objects with embed some behavior.
Have a look at should entity be dumb. Even if it's for java, the concepts are general.
EDIT
Here is my analysis based on your comment:
You don't have a domain model with entities. You manipulate the database directly.
What you call your model, is what I call services and is where you perform the business logic that manipulate data. Service classes are stateless, which is correct. As you pointed out in the question, you then either need to constantly re-create them, create one global instance, or use static methods.
The OO paradigm would say that you should try to have a domain model where you map your database with entities. At least have an anemic domain model where entities are dull data container that are loaded/persisted in database. Then the OO paradigm would also say to put a bit of logic in the entities if possible.
It would also say to turn the services into objects to ease composition and reuse. If it was the case you could for instance wrap all services with an interceptor to start/stop transactions or do some security check, which you won't be able to do with static methods.
What you describe (no entities + stateless procedural services) is not considered a great OO design. I would suggest you introduce an anemic domain model at least and DAO. Regarding the sateless procedural services, this is actually the reality of many web applications -- if you don't need more you can stick to it.
My 2 cents
If you are mainly only using static classes then you've really taken out the object out of object oriented programming. I am not saying you are doing things incorrectly, I am saying maybe your system shouldn't lend itself to OOP. Maybe it is a simple app that requires some basic utility functions (sends email, etc). In this case most of your code becomes very procedural.
If you are dealing with databases you could have a static db class, and a simple business layer, and your php app interacts with your business layer which in turn interacts with your database layer. This becomes your typical 3-tier architecture (some people like to refer to this as 4 t-iers and seperate the actual database from the data layer, same thing).
If you are not really calling methods that require an object than what is the point of all of these static classes, just a question to ask yourself.
One thing you may notice is that if you plan on doing any kind of unit testing with mocking/stubbing you are probably going to have a hard time since static classes and methods are not easy to mock, stub or test.
I would be cautious about using static variables and classes in web applications. If you really must share an instance between users, then it should be ok to have a single instance (lookup "Singleton" design pattern).
However, if you trying to maintain state across pages, you should do this through either utilising the ViewState or by using the Session object.
If you were to have a global static variable, you could have a situation where concurrent users are fighting to update the same value.
Short answer: It's ok but you are foregoing the benefits of OOP.
One reasoning behind using objects is that most of the time there is more than one type of object that performs a role. For example you can swap your DBVendor1 data access object with a DBVendor2 data access object that has the same interface. This especially handy if you are using unit tests and need to swap objects that do real work with dummy objects (mocks and stubs). Think of your objects with the same interface as Lego bricks with different colors that fit together and are easily interchangeable. And you simply can't do that with static objects.
Of course, the increased flexibility of the objects comes at a price: The initialization of the objects and putting them together is more work (like you wrote) and leads to more code and objects that put together other objects. This is where creational design patterns like builder and factory come into play.
If you want to go that route, I advise you to read about dependency injection and using a DI framework.
Technically there is nothing wrong in doing it. But practically you are loosing lot of the benefits of object oriented programming. Also write the code/functionality where it belong to.. for example:
user.doSomeTask()
on the user object makes more sense than
UserUtils.doSomeTask(User user)
Using OOP concepts you abstract the functionality where it belongs to and in future it helps you change your code, extend the functionality more easily than using the static methods.
There are advantages to using static methods. One being that since you cannot inherit them they perform better. But using them all of the time limits you. The whole OOP paradigm
is based on re-usability of base classes thorough the use of inheritance.

Categories