What are the benefits of caching instances of a class? - php

I have an application in which I repeatedly use the same (big) class. Since I use AJAX for that App, I always have to create a new object of this class. Someone advised me to cache an instance of this class and use it whenever it is required (using apc in a php environment)
What are the benefits of it ? is it really saving some time ?
$this->tickets_persist = unserialize(#apc_fetch("Tickets"));
if (!$this->tickets_persist) {
$this->tickets_persist = new Tickets_Persistance(); // Take long time
apc_store("Tickets", serialize($this->tickets_persist));
}

The benefits are only really realized if you are dealing with a class that has an expensive instantiation cost. If there is things that take a lot of time, memory or other resource being done in the constructor of the class (for example: reading an XML sitemap and building a complex data structure to build your navigation.) you can dodge this by leveraging caching.
It's also worth noting that resources (like database links and such) are not able to be cached and they would have to be re-established after the object is unserialized (here is where the __sleep and __wakeup magic method comes in).

It would only be worth it if your object requires a lot of processing during instantiation. Caching will not help you with "big" objects, it will help you when you want to avoid processing that can be repeated. In your case, it would only be worth it if your construct method required a lot of processing. Let's take an example of how caching would work in the context of a webpage :
On first page load, instantiate and cache the object for x hours
On any subsequent page load for the next x hours, it will directly return the object, without processing the instantiation
After x hours, the cached object will be expired, the next page load will re instantiate the object and re cache it
Your application will behave in the same way, the only difference is that you will "re-use" the instantiation process that has already been done.

Related

Laravel: Cache just for the script duration - similar to Session::flash

Does Laravel have any Caching mechanism to cache something just for the duration of the current script/request? Whether that's using a Cache driver like FileCache or DatabaseCache, or just in-memory cache.
For example, I have some data that is quite violate and changes often, and my scripts gets it in multiple places. So I would like to cache it once I got it the first time, but forget it after the execution of the current script has finished (so on next request it fetches it again).
It would be equivalent of me having some global variable $cache or similar, where I could store for example $cache['options']. Is there something like that in Laravel already?
Thank you.
One way is just following the singleton pattern for the class that does the repeated functionality.
You can also just bind an instance of a class to the Service Container and pull in that dependency where you need to use it.
https://laravel.com/docs/5.4/container
Singleton or instance binding would allow your application to share the same instance of a class anywhere during a single execution.

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.

Performance when Instantiating an object in php

I would like to ask about the performance and memory usage of instantiating an object in php.
On every php file of my application, i included a file which connect to the database.
$db->DB::getInstance();
$db->connect('all my credentials');
This is the getInstance() function in my db class.
//singleton database instance
public static function getInstance() {
if (!self::$Instance) {
self::$Instance = new DB();
}
return self::$Instance;
}
Currently everything turns out well. But i am concern of performance issues as in, can it be improved, possbile flaws etc.
I researched and found out that singleton instance can help to save memory. It will reuse the object if it's already been instantiate. Am i right?
My exact question is
E.g. if i have 10 users accessing the script, does it means that the object will be instantiate 10 times? When that happens, will it put 10 x load on my memory usage? -> this is pretty what i am interested in
Appreciate any expert advice.
As with all performance tweaking, you should measure what you're doing instead of just blindly performing some voodoo rituals that you don't fully understand. When you save an object in $_SESSION, PHP will capture the objects state and generate a file from it (serialization). Upon the next request, PHP will then create a new object and re-populate it with this state. This process is much more expensive than just creating the object, since PHP will have to make disk I/O and then parse the serialized data. This has to happen both on read and write.
In general, PHP is designed as a shared-nothing architecture. This has its pros and its cons, but trying to somehow sidestep it, is usually not a very good idea.
Do not use Singleton's, it makes testing a hell.
Objects are sent around the system in PHP as references by default. So you can simply share that Database connection object around other classes in the system without performance hit (it won't clone them until you specifically order it to be cloned).
But yes, if ten users use your system then that means you will have ten instances of that class. And it means that memory usage is ten times higher IF all the requests of users are active at the same time (well, usually, depending on load and server settings, some requests may have to wait until others are complete).
It is possible to tell PHP and database to use persistent connections, which means that other scripts that use the same database username and password and connect to the same database, share the 'connection'. But this is almost never recommended, since requests from one user may slow down the experience of another user who has to wait while the previous users database query has completed.
So, in short, do not use Singletons. In a smart object-oriented architecture, the class is passed to child objects or inherited from parents. This means that the class can easily be changed or a mockup can be easily created for testing purposes.

What should be an instance of a class in php?

In PHP 5.2.x, mySQL 5.x
Im having a bit of an issue wrapping my head around what should and should not be an instance of a class in php because they are not persistent once the page is rendered.
Say I have a list of comments. To me, it would make sense that every comment be its own object because I can call actions on them, and they hold properties. If I was doing this in another language (one that has persistent state and can be interacted with), I would do it that way.
But it seems wasteful because to do that I have a loop that is calling new() and it would probably mean that I need to access the database for each instance (also bad).
But maybe im missing something.
Php just seems different in how I think about class and objects. When should something be a class instance, and when not?
This is a subjective issue, so I'll try to gather my thoughts coherently:
Persistence in PHP has sort of a different meaning. Your thinking that each comment should be an object because comments have actions which can be performed on them seems correct. The fact that the objects won't persist across a page load isn't really relevant. It isn't uncommon in PHP to use an object in one script, which gets destroyed when the script completes, and then re-instantiate it on a subsequent page load.
Object-oriented programming provides (among other things) code organization and code reuse. Even if an object is only really used once during the execution of a script, if defining its class aids in program organization, you are right to do so.
You usually needn't worry about resource wastefulness until it starts to become a problem; if your server is constantly taxed to where it degrades your user experience or limits your expansion, then it is time to optimize.
Addendum:
Another reason defining a class for your comments is that doing so could pay dividends later when you need to extend the class. Suppose you decide to implement something like a comment reply. The reply is itself just a comment, but holds some extra attributes about the comment to which it refers. You can extend the Comment object to add those attributes and additional functionality.

Should I store my PHP5 Objects in session for SPEED, and why?

As you know, when you store a class defination in SESSION serialized automatically, and are unserialized on each following pages.
I just started to write classes and I wonder that:
to store a class in session or a file with serializing is a good idea?
If yes, how can I STORE and then GET to use a class in PHP5?
You don't store a class in a session variable, but you can store an object. Take note that if your object has properties referring to resources like file handles and database connections, no amount of unserializing will bring them back.
Unless it's a tiny class, probably not (see this question for possible pitfalls with large sessions). In short, sessions are not designed to be a caching mechanism, and they don't perform too well when you make them into one.
Note that if you are using the default session handler, your sessions are stored on the hard drive - not very fast when you get many concurrent requests. Also (test and measure), serialization/deserialization may be slower than the normal methods of object creation - note that you'd probably be deserializing twice: from session to string, then string into object of that class.
If you want to go the serialization/deserialization route, try e.g. Memcached instead.
Storing object instances in the session has the following disadvantages:
Performance overhead: Even if you don't need some objects, the will be unserialized and instatiated on every request.
Strange bugs in development: Whenever you add or remove a property from an object, the instance from the session will not match the object definition.
Security: Typically the session data is stored separately from your application. Sometimes this location is not as access-protected and secure as the rest of your files.
Data duplication and wrong state: With sessions you may store the same objects over and over again for different users. Compared to a dedicated object cache, where each object is only stored once, this leads to increased storage needs and the possibility that an object has the wrong state because the state was changed in another session.
I'd rather store the objects in a dedicated cache. Have a look at the Zend Cache class as an example of a good cache library.
If your object uses resources (database connections, files, gd images) your class should implement the Serializable interface. You then have to add two methods that do cleanup and initialization stuff.

Categories