Store domain model in PHP session - php

Is that a good practice to store the objects of the domain model in the PHP session ?
This would enable to avoid to query and reconstruct every PHP object to each PHP request.
Is there a size limit ?

If you use OOP in PHP you probably want these objects to be reconstructed at every request for several reasons.
All in all there wouldn't be much of a performance difference between storing, loading and deserializing the objects from the session, as you suggested, or just reconstructing them either.
It would depend much on the kind of the classes you use too, of course. Constructing a class usually isn't very problematic in terms of performance unless there is a real lot of stuff needed to do so (Database queries, etc.)
Additionally, doing so could make your code less understandable and/or maintainable too.
And yes, there is a size limited defined by the maximum memory usage of PHP set in the php.ini
So this question is not really answerable unless you exactly know what the classes you want to store in the session are, what they do and how they interact.
For example, if you were having a class which abstracts a logged-in user on your site, storing it's object in the PHP session would probably a good idea. In most other cases, however it wouldn't.

Related

What are the advantages to passing a global DB connection into each function of a model?

I am working with an older code base that passed a db connection into most functions in each class of the models. The db connection is created as a global and passed everywhere in the application:
$user = new User();
$user->loadById($db, $userId);
What advantages do we get by doing this vs a single connection the entire model inherits similar to the way most frameworks currently work?
Any insight would be very helpful.
Full Disclosure:
I asked this question this way because this is how we do it at work. I don't like that we pass around the DB connection. I am trying to find a proponent of this method to see if my mind can be changed. That is why I tried to sway the discussion to the PRO side of this conversation without being blocked as a bad question. And it worked. I didn't get banned, but the great StackOverflow community didn't let me down. It appears I'm not out in left field with how I think about this issue.
The main advantage is: it's easier. As in, it's the simplest thing to do, because as a result, you have no application architecture. You're grasping at things from everywhere and anywhere because you have no idea how to get them otherwise, and this makes for very poor maintainability. Guess what happens 5 years down the line with this sort of codebase? Massive legacy technical debt, and it's very likely your developers aren't using Object Oriented Programming - more likely shoving procedural code in classes.
I'm not going to bother explaining about global state, because there's already a fantastic answer that already exists on programmers. A small excerpt:
Very briefly, it makes program state unpredictable.
To elaborate, imagine you have a couple of objects that both use the same global variable. Assuming you're not using a source of randomness anywhere within either module, then the output of a particular method can be predicted (and therefore tested) if the state of the system is known before you execute the method.
However, if a method in one of the objects triggers a side effect which changes the value of the shared global state, then you no longer know what the starting state is when you execute a method in the other object. You can now no longer predict what output you'll get when you execute the method, and therefore you can't test it.
You'll find some developers do this purely out of laziness or a lack of knowledge / understanding of the basic concepts of SOLID. If you access global state (like the database), then the beautiful, isolated class you are currently writing that theoretically can be handed off to any other developer, and also tested in it's own right, is now coupled to this object somewhere off in the clouds.
As well as the above, you're making a liar of your object API. Each object should, via it's constructor / method signatures, specify exactly the required external objects with which it requires to function. This allows:
Your object to have a definitive API for it's usage
Future developers can see exactly what is required for this object to function from the constructor / method signatures
Everything passed in via Dependency Injection (the posh word for passing in parameters, basically), can be 'mocked out' for testability
Developers don't need to read through your code to find out what other objects are required, because of point 2
You aren't accessing something that can be changed by something else, somewhere else, and make debugging a nightmare
Your code should not be brittle. You should be completely confident in making changes somewhere in a massive codebase, without worrying about breaking something somewhere else. Your unit tests will cover this. I highly recommend reading The Clean Coder as it elaborates on some of these concepts.
AlmaDO has a picture of a good image about Singletons, which are basically objects that return a single instance of an object, like a database or logger. So if you request a new database from it, you either get a new one or just get back the one that already exists. In the traditional request / response / dead context, this is completely unecessary. If you're having a very long-running process, maybe this might be necessary, especially in other languages, but as a general rule of thumb in PHP; unless you're running a PHP web socket server or similar, DI is a much better way to go for maintainability.
This is exactly the same as calling StaticObject::Database, again - something that can be accessed from anywhere.
This is a really good post on Singletons in PHP, and how they're not at all needed - that post also has a lot of useful links in it further down.
Basically - don't be lazy and grasp SOLID. There's a reason it exists, and it's certainly not just for PHP, either. The main reason people do it is because they don't know better and it's easier, and easier isn't always the best way.
Also, a few additional clarifications. We don't have "models". We have a model, which is a layer. This is a massive misinterpretation of 'MVC', which we don't even actually have in PHP ('classical mvc'). We have the separation of concerns and that's it.
Your "models" are likely, services, domain objects, entities. More info on what the model is
Your user should not know about the database. It should be an Entity. Active Record Pattern is not the way forward. Take a look at DataMapper. Your repository would use the database object and return an array of User objects. Contextually as well, a user having access to the database makes no sense.
Most frameworks do not work by having access to the database in entities - this isn't PHP 4 any more, it's progressed a lot since then ;-) I highly recommend moving away from CakePHP (it's not MVC in any way) and take a look at a framework like Symfony, which still has it's flaws - knowing the flaws of your chosen framework is very important

Why do MVC frameworks in PHP not persist between requests?

What I have been able to grasp from reading the source and documentation from several PHP frameworks is that they generally don't persist, except for what you personally cache or throw into a $_SESSION var. Why is this? It seems a waste to essentially initialize the framework for every single request, would it not be better to at least serialize and store some core objects and variables to save processing and time?
At first I thought this was rather subjective and avoided asking, but everything I've read doesn't really speak about it at all, so there must be something obvious I'm missing.
The only real mention/discussion I've found of this is here which doesn't directly answer my question and some of which goes over my head a little.
Edit for Clarification: I am not asking about the inner workings of PHP, I know how persistence works (ie won't persist unless you make it through caching or session vars), I am asking why PHP frameworks don't do this for their core objects. Again it seems subjective to me, but as almost nothing I've read mentions it, and it seems to be fairly standard practice, I'd like to know what I'm missing.
Memory:
Most frameworks don't store these core mechanisms in $_SESSION due to memory concerns. Frameworks often generate variables / objects that can contain several megabytes of information. That may not sound like a lot, but scale that to a few thousand users and you've got a problem.
Data "Freshness"
The second issue with shoving framework components into memory is that they can become out of date very quickly. Instead of pulling an object out of memory, checking to see if it's outdated and then recreating it (if it's indeed outdated) is less efficient (most of the time) than just recreating it with every request.
I hope this clarifies things.
If you want data to persist between server requests then you need to use cookies/sessions or store your data in a database. This is just the way that it works. PHP cannot store data in itself for use between server requests.
Some frameworks may store core objects in a database or to a local file on disk, but it would depend on the framework.

Is it common practice to keep PHP objects alive by storing them in session variables?

I'm new to OOP using PHP and the idea seems a little pointless in some ways. In non-webbased languages the object lives through-out the life of the program (from execution to exit). In this situation it make perfect sense because you build the class then initialize it at run-time where you can access it frequently as needed there after. However with web programming since the execution of an application might happen in many stages (page loads) the life of the object could end up being only a small portion of the time an application is being run. So it seems to me that the only option to keep objects alive during the course of the application's usage would be to store that object after initialization in a session variable. Is this common practice or are there other means by which to utilize the power of OOP in PHP more effectively?
PHP's website has an article that deals specifically with this: Serializing objects - objects in sessions. There's absolutely nothing wrong with serialize objects in your session but as this article suggests:
It is strongly recommended that if an
application serializes objects, for
use later in the application, that the
application include the class
definition for that object throughout
the application. Not doing so might
result in an object being unserialized
without a class definition...
It can still be very useful to manage objects with short, time-limited lifespans. Perhaps you want to communicate with two different kinds of database servers -- having objects that know how to build queries for those database servers can be very convenient. You, the programmer, get to interact with them in the same way, but behind the scenes one might use a unix domain socket to talk with a local PostgreSQL and the other might use a TCP connection from a session pool to talk with an Oracle instance.
Object-oriented programming exist to provide encapsulation and abstraction. Both are useful, even if the objects involved are created, live, and die, in .5 seconds.
With PHP you cannot keep an object alive, so you cannot store it in the session to gain performance. PHP will always serialize the object when writing to the session and deserialize it reading from the session.
To answer your question, yes it's very common to store an object in a session, but not for performance reasons. Storing and reading from the session are quiet fast, so i would only look for optimizations there, if you are sure this is a bottleneck.
Somethings to make sure you do if you take this approach is make sure your garbage collection is thoroughly working. Depending on what the object does it may store as quite a large record in which case you will be taking up quite a bit of disk/database storage.
I am a Codeigniter fan but those objects are huge and it would be highly unwise to store them. Security is another factor - if you are on a shared server and there is a chance of security credentials being held in the object then storing these may also be unwise.
I do store objects in a database but just make sure Garbage collection is working. If you use a database there is a bug in Ubuntu where the collection doesn't run - in which case you need to force it through ini_set.

Why use classes in php?

I want to know why we use classes in php. I have seen in all of open source they use classes for executing query. It means they use classes for getting results, insert query etc. I think this is used for consistency and speedup, but as my knowledge if we execute query using mysql_query(), rather than creating an object link $db->query will execute fast as compare to second one because in object it will goto the function and then it execute it there and after that it return the result but in case of mysql_query() it will execute the query on the same place. So I think mysql_query() will execute fast. So why we use classes and object to execute query, what are the benefits of using classes?
Encapsulation: A class is a useful packet containing the code and the relevant data together, isolated from everything else. That makes it easier to move it around without searching for exact variables, without collisions with existing code/data.
Of course classes have other uses but in scripting environments like PHP, I think the biggest advantage is that.
EDIT: I was objected with "inheritance is more powerful than encapsulation" argument. I think that does not apply to scripting and web scenarios and I'll try explain why:
First, a web page's lifetime is a request/response pair and ideally less than a second. The state is usually preserved in external entities (session, cookies, db etc). Since the page's lifetime is very short, possible states in a web page code are less than, say, a fat client. It's almost always small bursts of code running and finishing the work continuously. Arguably a web page is comparable to a console application in terms of simplicity and number of design parameters. Although number of input parameters can be gigabytes in a form, the relation between UI elements and input parameters are limited to screen resolution, a user's overall capability to what he/she can fill in at once. Therefore in majority of cases we have small number of input parameters, meaning smaller number of states. Of course in combinatorial and "mutable" world that's not true but in the case of "typical web applications", internal state is also small, hence making my claim plausible.
The input and output in a web application is mostly the same: Input is query parameters or form data and output is an HTML document. Therefore in its short lifetime the input processing and output production code is similarly shaped and designed for a web page. I am aware that I omitted a big chunk of "business logic" in the picture and I'll get to that. However let's make sure that we have no use of nifty features of OOP like "polymorphism" and "inheritance" in these parts of our code. There are very well known, long studied, practical and non-OOP patterns for that. It would be at least dumb to invent new ways of parsing query parameters using "polymorphism", "visitor pattern" etc.
The data access is also performed by existing libraries and luxuries like "inheritance" or "polymorphism" have no use there. You can still use classes but that would simply be encapsulation. You can't inherit/reuse MySQL code for writing T-SQL or PL/SQL code. You need a complete replacement. Oh maybe your SELECT * FROM table could be "inherited", and think of possibilities, wow.
Now what we have left? Yes, the business logic. We already mentioned that business logic is also short bursts of information processing. There is no persistent business state in PHP code itself. We know that almost all business operations must take less than a second due to The Web's requirements. Therefore the states you can go through, again, is much less than a full fledged application. You have atomic, isolated business operations going on for majority of cases in a typical web application.
Now let's go back to design. We know that our page consists of these parts:
Input
Business logic
Data access
Output
We already got input, data, output out of the scope of polymorphism and inheritance. Here is our final picture:
Input processing
Business logic
Data access
Output production
Although business logic could be the biggest part of our app, it's still got to be in our one second window in a web application therefore has to be small, aka short lived.
Yes a supercomputer can do a lot in a second but we're still talking in terms of majority, common scenarios. What's common? CRUD is common. That's why Ruby on Rails and Active Record pattern is such a success and gained such a popularity because it increased productivity on one thing: CRUD.
The complexity of a design is proportional to the number of data elements and operations involved. And since we assume that majority of operations are CRUD, we have a fixed number of operations and small number of input parameters, we have a small problem space.
There can be exceptions but for most of the cases a design for a small problem space can't be complex and good at the same time. It's very unlikely that you can use inheritance in a web page's design unless there are vast amount of data points and too much redundance going on behind. I repeat, for most of the cases, it's crude CRUD.
Second, (yes there was a first at the beginning in case you forgot), web app performance is important (if not critical) -remember "one second"- and in a scripting environment it's twice as important.
Object-oriented paradigm relies on a very important low-level mechanism for being useful and performant at the same time: pointer indirection. The ability of a CPU reading pointers and jumping to the address pointed by it with almost no difference than jumping to the address directly. That way we can have a virtual method table used for lookups for correct function call and that way compiler can call object's "some()" method without knowing it's exact type because it's just whatever is in the pointer there, yet it still performs like a crazy horse.
That dream ends in the scripting world. You don't have a CPU natively executing instructions. You have bytecodes produced by PHP compiler and that is interpreted by PHP interpreter. Unlike a CPU, PHP interpreter has to deal with higher level concepts like abstractions, classes, types regardless it's a bytecode. The simple pointer indirection for a CPU is a complex set of operations for PHP. Parsing the operation, understanding the operation, making some sanity checks maybe, and finally performing it with another set of bytecodes.
Therefore the overhead of inheritance in a scripting world is orders of magnitudes slower than in a native environment.
That is acceptable of course, as long as gains are more than losses. And thinking of that the performance loss can be recovered in other ways like upgrading, clustering, it doesn't seem like a problem. That's certainly true and here is my final statement:
For most of the scenarios in web application development, an equally maintainable, equally reusable and possibly more performant design could be achieved without calling upon inheritance/polymorphism, therefore encapsulation is the most common and the greatest benefit in PHP, not inheritance.
There are many reasons for using classes, or OOP (Object Orientated Programming).
Code reuse
Inheritance
Easier maintainability
Encapsulation
There are many more reasons, you should just look up the advantages/disadvantages of using OOP.
Time taken my
$db->query()
mysql_query()
is almost the same.
We do not use classes to get execute the code faster but to organise them.
As your project gets bigger and bigger, you will have difficulty in managing your code.
If you objects then you can instantiate that object and use them again again, and besides your code has less chances to get messed up with others.
Object Oriented Way of coding is the easiest and best practice for managing your code elegantly and hence produce better results.
When we use mysql_query() you have to connect before to the DB with mysql_connect() and mysql_select_db().
Everytimes you make a mysql_connect() it cost.
So you will make one time mysql_connect() and save the $link. And use this link for every mysql_query("...", $link)
In object it's the same but it's more elegant you juste create an instance of the class (so it create a connection to the DB) and use the object has a link.
If you change the DB password, you will change it one time, just in the class.
If you change MySQL for PostgreSQL, you will rewrite your code one time, just in the class. It will not affect the rest of your app.
As #frbry said, we use classes for abstraction. Abstraction is needed to manage and reduce complexity. When you are able to "abstract" operations and data, you are able to focus on other things and not think about the implementation of the "isolated and abstracted" things, when doing other things.
It also helps to change the system in the future with smaller impacts on other parts of the code, and again reduce the complexity of a system.
There is a very good MIT lecture from 1986 that is generally about LISP programming, however it also very well describes, why you need to abstract things in procedures (or black boxes they call them) - the point they make is that software development is all about reducing complexity.
Here is the link: http://www.youtube.com/watch?v=2Op3QLzMgSY

PHP OO vs Procedure with AJAX

I currently have a AJAX heavy(almost everything) intranet webapp for a business. It is highly modularized(components and modules ala Joomla), with plenty of folders and files. ~ 80-100 different viewing pages (each very unique in it's own sense) on last count and will likely to increase in the near future.
I based around the design around commands and screens, the client request a command and sends the required data and receives the data that is displayed via javascript on the screen.
That said, there are generally two types of files, a display files with html, javascript, and a little php for templating. And also a php backend file with a single switch statement with actions such as, save, update and delete and maybe other function. Several pages/screens may use the same php backend.
Recently, I have been adding an server sided undo function that requires me to reuse some code. So, I took the chance to try out OOP but I notice that some functions are so simple, that creating a class, retrieving all the data then update all the related rows on the database seems like overkill for a simple action as speed is quite critical. Also I noticed there is only one class in an entire file.
So, what if the entire php is a class. So, between creating a class and methods, and using global variables and functions. Which is faster?
Writing object oriented PHP will not affect your performance at all. If you use extensions like Zend Optimizer, it can even work faster.
So, there's really no reason not to use the much cleaner and more easily maintainable object oriented paradigm in PHP.
Writing purely procedural code may even lead to a performance drop since optimizations can be much harder and small details that eat up execution time are more likely to occur in such a messy environment.
The question is misguided. The problem is not one of speed, it's one of code organization. Using only global functions and variables, and lots of them, it'll get harder and harder to avoid naming conflicts and keep everything organized. Classes help you package and abstract things. Execution speed is a secondary concern, and in most cases won't increase noticeably, if at all. Development speed though can increase significantly over time, since you'll have to deal less with conflicts.

Categories