PHP serializable interface - php

I am trying to persist a large class called an Authorizer which holds a reference to a database connection and a container of other objects representing the result of a complicated set of database queries. I want to serialize the expensive to build parts of this object in a session. Then when I need to ask the Authorizer a question I want to wake the Authorizer object up instead of building a new one for each page. I am writing a custom handler to temporarily store this object in a database table. I understand that the magic method __sleep() is usually used to handle choosing which parts of the object to store and then __wakeup() is used to restore the database connection.
This is where I get fuzzy. I think serialize() and unserialize() are supposed to work instead of the constructor and destructor, but I can't quite understand how they interact with __sleep() and __wakeup(). Then I got to the part of the manual describing the serializable interface and thought OK I will be able to implement this and be sure I have this right. Then I read that classes which implement this interface no longer support __sleep() and __wakeup()! That was the only part of this whole thing I really understood >:-{ I couldn't find any examples at all of how to properly implement this interface.
So my question is what is the preferred way to implement serialization in a completely object oriented system? Is the serializable interface meant to replace an older method? What is the purpose of having two different sets of functions (_sleep()/_wakeup() and serialize()/unserialize())?

__sleep and __wakeup are called by the default serialize/unserialize methods to prepare the object for serialization. This works in the case where the default PHP method does close to what you need and you simply need to perform some cleanup around the process.
If you're implementing the Serializable interface, then there's no need for these methods are you're declaring that you are implementing the entirety of the serialization process yourself. So any work which would normally be done in __sleep would be incorporated into serialize, and the same with __wakeup and unserialize.

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.

Should I pass a PDO object to every object, or make a new one for each object?

I've done mostly procedural programming for years and am trying to wrap my head around OOP and PDO. I've started converting an application I've written to using classes instead of standalone functions (it's a nightmare, but I think it will be worth it..) and would like to use PDO instead of the regular mysql_* functions. I'm kind of flying by the seat of my pants, just learning as I go along, and I'm not sure how I should handle the PDO object(s).
I know it would be stupid to create a new PDO object every time I need to make a query, so that leaves two ways that I can see:
Creating a PDO object in each class (i.e. every time an object is created, call a member function to create a PDO for it to use).
Create PDO object at the beginning of my application and pass it to the constructor of every object that is created, and all the objects share the PDO object.
What is the best way to do this?
Thanks for your advice!
Don't make more than one. You'll go crazy trying to manage all the DB connections.
One good solution would to make a singleton object for data access and retrieve it via it's static accessor method whenever you want to use the DB. That way you only ever have one place that manages DB access and PDOs. If you want to be a bit more MVC about it, you can put all SQL code in there too.
Depending on the size of the application, you probably want to use a Singleton to handle your database connection. Essentially, this will be a class that wraps your database connection and has a static function that will return your PDO object. However, because it's a Singleton it will only ever create one (assuming you don't make it more sophisticated). This saves you both from having to continuously make objects and from having to pass one object into all your objects, properly decoupling persistence from business logic.

php: object autoload - is it worth?

I successfully managed to "autoload" objects: if I override the __get() method, I can just create the object. We seen that class autoloading does have advantage. But does object auto creating have too? Until now I had that object references (they both were private and public) and if I remove the reference, it becomes public automatic. And the other hand, code completition doesnt work anymore. I would say, this strongly ruin the object-class structure (no property).
So, does it comes handy? Can I gain more speed with it?
You can under given circumstances gain a speedup, if you lazy-load objects from a database or a webservice, or anything that takes long to load. The speedgain does however not come from the __get or __set methods, but instead from avoiding to load data, that is not actually required. __get and __set are only language constructs that give you more opportunities.

PHP serialization with non-serializable parts

I have a PHP class that stores database query results, but also contains a PDO object so that the results can be updated/re-inserted/etc on the fly. A makeshift ORM, if you will.
Problem is, I need to serialize this class but instances of PDO cannot be serialized. I'm ok with that; by the time the object gets serialized, I have no need for the PDO instance.
Is there a way to mark a variable for exclusion from serialization within a class, like there are with some other languages? I understand I could manually unset() the PDO variable before I want to serialize the class, but with the current structure of the code, that would be a bit of a nightmare.
My saving grace here would be a __serialize() method that could be overridden, but it doesn't appear anything like that exists.
There's __sleep() and __wakeup().
Alternatively, you could implement Serializable.
Starting with PHP 7.4, there is also __serialize and __unserialize (see the Documentation) as a more usable alternative.
The Serializable interface might also be deprecated, and generally the magic methods are preferred (see also this).

correct use of 'construct' when designing classes

I am new to object oriented programming and writing some of my first classes for a PHP application.
In some of the simpler classes, I declare a function __construct(), and inside of that function, call certain class methods. In some cases, I find myself instantiating the class in my app, and not needing to do anything with the resultant object because the class's __construct() called the methods, which did their job, leaving me nothing left to do with the class.
This just doesn't feel right to me. Seems goofy that I have a new object that I never do anything with.
Again, I'll stress this is only the case for some of my more simple classes. In the more complicated ones, I do use class methods via the object and outside of __construct().
Do I need to rethink the way I coding things, or am I ok?
Well, the constructor is used to create a new instance of a class, and to do any necessary setup on that class. If you're just creating the class and leaving it, that does seem a bit of a waste. Why not, for instance, use static functions in the class as an organizational tool and just call them(or a function that calls them) instead of constructing a new instance that you'll never use?
This just doesn't feel right to me. Seems goofy that I have a new object that I never do anything with.
Yes, that should raise a red flag.
In general, you should not let constructors have any side effects; They are meant for initialising the state of the object - not for anything else. There are of course exceptions to this rule, but in general it's a good guide line. You should also abstain from doing any heavy calculations in the constructor. Move that to a method instead.
Side effects are many things - Changes to global variables or static (class) variables; output to the environment (For example calls to print(), header() or exit()); calls to a database or other external service and even changes to the state of other objects.
A side effect free function is also called a "pure" function - as opposed to a procedure, which is a function that has side effects. It's a good practise to explicitly separate pure functions from procedures (and perhaps even label them as such).

Categories