PHP Omit Variables from Serialization - php

Is it possible to omit certain variables from serialization? Say I have a temporary variable in a php object that I don't want serialized as it is a waste of space. The only thing I can think of is making them static but this is not ideal as it is not really part of the object which there will be many instances of.
This may not even be possible but would love to hear some ideas.

Take advantage of the __sleep method of your object.

Related

Class-to-class passing of data, optimization

I have written a file-handler-class, that works like this:
__construct opens and ex-locks a file, reads its json-content and parses that as an PHP-array, keeping this as a property of the class.
The file is still locked, in order to avoid race-conditions.
Other 'worker-classes' make changes in this Array, in/from other scopes.
__destruct encodes the finished Array, writes it to file, and unlocks the file.
Everything works fine ...
QUESTION:
Is it sensible to keep the Array as a property of the original class, or is it better to pass the Array to the worker-classes, and let them return it at the end?
Perhaps there is a way to keep the Array locally, and pass it to worker-classes by reference, instead of as raw data?
I mean ... this is a question of not having duplicates, waisting memory. A question of speed, not passing things unnecessarily. And a question of best practices, keeping things easy to understand.
Actually, by passing the array to another function, having that function modify the array, and then return it to some other caller that may or may not also conduct modifications on it, you are in fact copying that array multiple times (since this invokes copy-on-write semantics in PHP) and by definition wasting memory.
Whereas by keeping it as a property of the object instance, you would not be invoking any copy-on-write semantics, even if the caller is not the same instance. Since passing an object instance won't copy the array, nor will its modification from said instance.
Not to mention you just make it easier to retain state within that object (assuming you care about validation).

why not use arrays instead of many parameters

I may sound stupid to some but I want to know if there is some benefit of passing arguments to a function as an array,rather than passing each arguments or some downsides?
Unwritten rule for good programming practice is that function should not have more than 3-5 arguments.
Usually arrays or even objects are used to pass in the logical complete data structures.
I think this is due more transparent and readable code rather than any performance benefits.
Sure it might look nicer if you pass an array to a method, but what does it mean?
Arrays usually signify that you have a collection of the same thing, whilst method parameters are usually different things.
If you want to pass a list of things to a method and do the same action on all of them, then it makes perfect sense to use some type of array/collection object.
If however you want to make it tidier and avoid passing around lots of objects together, consider refactoring your code to use some kind of wrapper object that you can pass around more easily.
Also if you have so many arguments that you would consider using an array to hold them, it's a sure sign that you need to refactor your code ;-)
Mostly it just requires more typing to create an array and pass it, rather than just passing individual arguments.
Other than that there's no particular specific advantage to separate parameters.
Parameter list much more clear when you read function signature. Array is just one variable, say, $args. But what there in args?
if you have this array already, it is surely better to use it.
if you don't have this array already, using parameters will save you typing of array keyword and a couple of braces.
that's all.
Use whatever you feel more suitable for the case.
I think that when you have a few parameters or less than 5 (subjectively) then more useful is passing arguments as parameters. If you have a big count of arguments then using array is more useful that function/method with 15 parameters.

Functions by reference or by variable, which to use when?

Well, I read in my handy PHP book that it's very important to be able to distinguish between reference and variable parameters. The book says that the original value of parameterized variables are preserved when the variable is changed, and the original values of parameterized references change when the reference is changed. It says that's the key difference, if I am reading right.
Well, I'm wondering when each is more useful than the other. How do I know when to use variables and when to use references when I create my own functions?
It's pretty straightforward. Use references when you need to modify the value of the variable passed in to the function. Use variables when you don't need to or want to modify the value.
So, for example, if you're writing a function that takes an array and changes that array, you'd be better off using a reference for that array rather than returning a new array from the function.
"References" (variable aliases) make your code harder to understand and could be a source of hard to follow errors. There are no valid reasons to use references in php and to be on the safer side try to avoid them altogether.
And no, objects in php5 have nothing to do with "references".
"References" as implemented in php is a strange concept. Normally, in programming languages variables are independent of each other so that changing one variable doesn't affect others. Php "references" allow several variables to share the same value and to be dependent of each other. Basically, you change one variable, and suddenly another one, which you think is totally unrelated, is getting changed too. It's no good thing and often leads to much confusion.
Objects in php (do I need to add 'five'?) have nothing to do with "references" in the above sense. They behave much like C pointers (actually, this is what they are under the hood) - when you pass an object to a function, you actually pass a pointer, and the function can use this pointer to manipulate the object contents, but there's no way for the function to change the passed variable itself, for example, make it point to another object.
This "objects are references" misunderstanding is probably because people confuse php "references" (ampersand syntax) with the generic CS term , which also applies to pointers, handles etc.

Drawbacks of static methods in PHP

In a theoretical database access class, I found that there are quite a few helper functions that I use in the class, which have nothing to do the class's instance (and others, that could be manipulated to be unrelated to the class's instance using dependency injection).
For example, I have a function that gets a string between two other strings in a variable. I've been thinking of moving that to a String_Helper class, or something of the sort. This function has already been made static.
Also, I have a function that queries a database, query($sql). The connection details are provided by the instance, but I've been considering making it static, and using query($sql, $connection). Developers would then be able to call it statically and not need to instantiate the database class at all.
For me, the questions are:
Is it worth it to do something like this? Functions like the query function make me wonder if this is not just me trying to make everything as static as possible, without any real need to. Under what circumstances would you consider this useful?
I know static functions are harder to test, but if I make sure that their code is completely dependency free (or uses dependency injection where necessary), then they're just as easy to test as everything else, surely?
It isn't a concern at the moment, but if, in the future, I decided to extend the classes with the static functions, it would be impossible for me to make the current code use my extended functions. I've thought of Singletons, but the same problem arises: the code would be calling Singleton_Class::getInstance(), and not My_Extended_Singleton_Class::getInstance(). Dependency Injection seems to be the only way to solve this issue, but it might lead to a clunkier API, as every dependency has to be given to an object on __construct().
I have a container class, which holds certain pieces of information statically so that they can be accessed anywhere in the script (global scope). If I can't use static functions or singletons, a class that contained instances of different variables would be great. One could use for example Container::$objects['MyClass'] = $MyClass_object;, and then the rest of the code could just access Container::$objects['MyClass']. If I extended the MyClass class, I could use Container::$objects['MyClass'] = $MyExtendedClass_object;, and the code that used Container::$objects['MyClass'] would use MyExtendedClass, rather than MyClass. This is by far the best way to do it, in my opinion, but I'd like to know what you think about it.
Ok, let me answer these one by one...
1. Is it worth doing something like this
Yes and no. Splitting out the helper functions into their own classes is a good idea. It keeps the "scope" of each of the classes rigidly defined, and you don't get creap. However, don't make a method static just because you can. The query method is there to make your life easier by managing the connection, so why would you want to lose that benefit?
2. They are harder to test
They are not harder to test. Static methods that depend on state are harder to test (that access static member variables or global variables). But static methods in general are just as easy to test as instance methods (in fact, they can be easier since you don't need to worry about instantiation).
3. Extending the classes
This is a valid concern. If you put String_Helper::foo() in the class itself, you'll run into issues. But an option would be to set the name of the string helper as a class variable. So you could then do {$this->stringHelper}::foo() (note, PHP 5.3 only). That way to override the class, all you need to do is change the string helper class in that instance. The Lithium framework does this a lot...
4. Global Registry
I would stay away from this. You're basically just making every class a singleton without enforcing it. Testing will be a nightmare since you're now dependent on global scope. Instead, I'd create a registry object and pass it to classes via the constructor (Dependency Injection). You still accomplish the same thing since you have a store for the objects/classes, but you're no longer dependent on a global scope. This makes testing much easier.
In general
When you're looking at doing things like this, I like to stop when I hit questions like this. Stop and sit down and think *What actual problem am I trying to solve?". Enumerate the problem explicitly. Then pull our your supposed solutions and see if they actually solve them. If they do, then think about the future and if those solutions are really maintainable in the long run (Both from a bug fix standpoint, and with respect to feature additions). Only if you're happy with both of those answers should you even consider doing it. Oh, and also remember to keep it simple. Programming is not about making the most complex, most clever or most amazing solution. It's about making the simplest solution that solves the problem...
I hope that helps...
Good Luck!

Function vs Objects Best Practice

I am wondering whats the best practices regarding functions and objects. For example I want to perform an action called tidy. It will take my data as input and tidy it and return it.
Now I can do this in two ways. One using a simple function and the other using a class.
Function: $data = tidy($data);
Class:
$tidy = new Tidy();
$data = $tidy->clean($tidy);
Now the advantage in making it a class is that I do not have to load the class before. I can simply use the autoload feature of php to do so.
Another example is the database class. Now everyone seems to be using a separate class for db connectivity. But we usually have a single object of that class only. Isn't this kind of contrary to the definition of class and objects in a sense that we are using the class only to intantiate a single object?
I kind of dont understand when to use a function and when to use a class. What is the best practice regarding the same? Any guidelines?
Thank you,
Alec
For something that does one thing, and only one thing, I'd just use a function. Anything more complex, and I'd consider using an object.
I took the time to poke through some piles of (arguably ugly and horrible) PHP code and, really, some things could have been done as objects, but were left as functions. Time conversions and string replacements.
Functions typically do one specific task.
Objects represent something that have tasks associated with it. (methods)
Use a function for tidy. Plain and simple. ;-)
I'd personally make a 'data' object that handles data then have a tidy method under it.
This pattern will allow the number of tasks you do on data to expand while containing it all in a nice little self-contained chunk.
For your case, I'd make it a function, possibly a static function in something like a "util" class (for which the only purpose of the class is to act like a namespace - it'll group all your random useful methods together). As a rule of thumb, only use an object if it needs to store some data that needs to live between multiple function calls. That's why the database methods are made to be part of an object, because they store a database handle which is used between multiple function calls. Yes, there only ever is one database object, but having it as an object groups all the database-related stuff into one place, making it easier to maintain and keep bug-free.

Categories