Passing object through constructor or method - php

So I have an object that could hold a string which contains some data, I have to validate the object or string but I cannot think why I would pass it into the method rather than the constructor, is there certain cases when I should pass it through the constructor rather than the method or through the method rather than the constructor ?
This is PHP code.

Constructor is also method differences is just in its usage. There are some things that we need to do at creation of an object of some class so for those things we pass object/setting arguments to constructor and when we need to process some data in context of that class we use method.
I think this was what u wanted to ask "difference b/w usage of method and constructor". If you got some coding issue tell me the scenario.

Pass an object into a constructor if you need it to be saved in the object for later use by one or more methods. Then, if you assign it, or a copy of it, to a member variable, it becomes part of the object's "state".
If the object to be passed is transient, and you only need it for the lifetime of the method, then you can pass it as an argument to the method.

Passing an arg through an object constructor has only one nominal benefit, and that is you are removing the extra step of calling setter(s) directly.
$foo = new Foo($dbo);
// Same thing as
$foo = new Foo();
$foo->setDbo($dbo);
Personally, I prefer to call setters explicitly rather than pass them through to the constructor because I don't want to end up with 15 signature arguments, and I can see how the calling code is using the object.
From time to time, I do use constructors for preparing related objects, but never for passing arguments.

Related

Magic Functions in PHP and their use?

i have been reading about magic functions lately, and I'm really confused about their implementations. Some Magic functions such as __contruct() and __destruct() are very useful. Magic functions like __construct() could be used to initialize variables with default values.
However I'm really confused with the implementation of other magic functions such as __isset(), __call(), __toString(), etc. What is the actual purpose of implementing the Magic Functions.
Yes, I do understand they are invoked behind the scenes and do not require a function call, but then what is their main advantage in real world, in terms of security-sql injection-scope. The main difference between isset() and __isset() (or any other Magic Function) and the situations in which I should use them?
You shouldn't use magic methods in PHP unless you want some documented magic functionality.
They allow you to react to certain events when using these particular objects. This means when certain things happen to your object, you can define how it should react in that instance.
Each of these methods are triggered automatically and you are just defining what should happen under these circumstances.
Probably you won't ever need to use any of them besides __construct() and __destruct() when dealing with objects.
__construct() - Is called when an object is first created. You can inject parameters and dependencies to set your object up.
__destruct() - Is called when an object is destroyed. You can write some cleanup code here. Closing any open datastreams, database connections... whatever.
__get() - Listens for get requests of the properties.
__set() - Listens for set requests of the properties.
__isset() - Triggered by calling isset() or empty() on the object's properties.
__unset() - Triggered by calling unset() on the object's properties.
__toString() - Allows you to define how an object will behave when it's treated like a string.
__sleep() - Code defined here will run before you use serialize(). So you can define which properties of the object should be serialised.
__wakeup() - This is used to reinitialize any tasks that may have been put to stop during the serialization.
__invoke() - Defines how your class should behave if you "invoke" it and use it like a function.
__clone() - Triggered when cloning an object is finished. (If you copy your objects they are still linked to their original as they are still referencing it. Cloning can get you a clean copy.)
__debugInfo - Triggered when using var_dump() on the object. You can use it to control what kind of info should show up in the dump. If the method isn't defined on an object, then all public, protected and private properties will be shown.

How can I pass an argument to the dependency injection container?

I have a class called GeneralReport, implementing HttpAccessibleDataGathererInterface, with a constructor and a method called calculate() that builds an array of plain PHP objects, containing the fields for a report. GeneralReport accepts two constructor arguments: one is an array of parameters, which contains the input used to construct the query. The second argument is another class, GeneralReportQueryBuilder, to build the query for the report based on the first argument.
Now, I would like the second argument to always be injected (I.E. the GeneralReportQueryBuilder). However, I want to somehow be able to pass in the first argument to the GeneralReport class in my controller. Keep in mind that the GeneralReport class implements an interface, so passing the array as an argument to the calculate() method is not an option. Also, since calling this class without an array of input would be pointless, it is not an optional dependency and creating a setter for it wouldn't make sense.
I would like to make the dependencies of GeneralReport clear and concise using its constructor, and don't want the DIC to get in the way.
There is a difference between :
creating a instance without X parameter
using an instance without X parameter
The first assertion is resolved by constructors parameters, the second by throwing an exception if during execution the parameter is not filled or valid!
Contextual parameters can be sent by setters !

In PHP, how can I unserialize into the current object?

This is probably a noob question, so please be kind.
I'm trying to implement a cache on an expensive "activity" object. In the constructor I first check the cache to see if this Activity instance already exists. If not, I do all the queries to build up the object, serialize it and save it to cache. The next time I come in, I check the cache and my object is there, so I unserialize it. Now is my problem, how do I put that object into $this, the current object? I can't just say "$this = unserialize($row[0]);" That fails with the error message, "Cannot re-assign $this in ActivityClass.php". What am I missing?
Thanks a ton!
Mike
If you don't want your construction to leave the class, you can create a factory method:
class Activity
{
public static function Create(/* your params */)
{
// construct cache and key, whatever
$obj = unserialize($cache->get($key));
if ($obj) return $obj;
return new Activity(/* params */);
}
// rest of your stuff
}
You'll have to serialize only your object's internal state, i.e. its parameters (aka "member variables"). In fact, in this instance, serialize() isn't really what you want to do; rather, you want to store your ActivityClass's data to your cache, not the serialization of the entire object. This gets tricky, though, because as you add new parameters later you need to remember to store these in your cache as well.
Alternatively, you can implement a singleton or factory pattern for your ActivityClass. Since you say you're pulling the class from the cache in the constructor, I take it that only one instance of this class is meant to exist at any given time? In this case, you should make your class a singleton, by doing the following:
Make the __construct() method private or protected.
Create a public static method (I tend to call this getInstance()) that will check your cache for the object, or instantiate a new one and then cache it.
Now instead of directly instantiating a new ActivityClass object, you instead write $foo = ActivityClass::getInstance();, which gives you either a new object or unserializes and returns your cached one.
As you noticed, you cannot just override the current object as a whole.
Instead, a possibility would be to store the data you're serializing/unserializing into a property of your object.
This way, you wouldn't serialize your whole object, but only one of its properties -- and only that single property would be overriden when unserializing.
Typically, you wouldn't serialize the connection to the database, which could be another property of your object.
Another possibility would be to not have your object deal with its own (de-)serialization.
Instead, you should :
Use an external class to instanciate your object
With that external class being responsible of either :
Loading data from cache and pushing it into your object,
Or calling the right method of your class, to load data from the database -- and, then, save that object to cache.

PHP sharing objects, do they get updated in another class?

I'm wondering; lets say you start an object in a new class; at the beginning of your app.
If you later pass that object into another class; as a variable and add/modfiy something on it. Will it be updated in the original object and its home class?
Or does it become a 'new' object, a different object in a new class? And will it continue to be the same throughout their uses. In either part of the app?
This is for my own clarification, as opposed to a specific coding question.
objects are passed by reference in php5, so the object is "updated", unless you clone it.
An object doesn't start, it is instantiated, it becomes an instance of a class.
You can't pass an object to a class. You can pass it to a function or a method, with no difference in these 2.
In every language with proper OOP, objects are passed as reference, so any updates anywhere on that object is reflected everywhere. It's an object, you pass it, modify it, and it remains modified.
You should reread what classes are. Obligatory car example ahead:
Imagine a class Car. Now you create a new instance of that abstract concept:
$myCar = new Car();
$myCar->color = "blue";
$yourCar = new Car();
$yourCar->color = "red";
Every object has its own properties. The class may set default values in its constructor functions, but changing one car's color to orange doesn't impact any other car.
In php5 (php4 oo is weird, I wouldn't suggest it to a beginner), every time you assign from a variable that contains an object, the object reference is copied. Therefore, after executing
$ourCar = $yourCar;
$ourCar->color = "yellow";
, $yourCar->color is "yellow".

How to explain 'this' keyword in a best and simple way?

I am using 'this' keyword for a long time. But when someone asks me to explain it, I am confused that how to explain it. I know that I can use this in a method of class to access any variable and method of the same class.
class MyClass{
function MyMethod1(){
echo "Hello World";
}
function MyMethod2(){
$this->MyMethod1();
}
}
Is it a object of a class that we don't need to initialise and can be used only within the class or anything else. How to explain?
Thanks
A class is a mold for an object: it specifies how the object looks like (variables) and what it can do (functions).
If you instanciate a class: you create an object. If you create the class, you can use "this" to refer to the object itsself. This is why you can't set the "this", because it's related to the object. It's a special, read-only variable.
this references the current object instance of a class.
this is an implicitly parameter passed to the methods of a class: it is scoped to a method and allows access to all of the object's members.
Like their name suggests, instance methods operate on instances of a class. How do they know which one to operate on? That's what the this parameter is for.
When you invoke an instance method, you're really invisibly passing in an extra parameter: the object to invoke it on. For example, when you have this:
class Basket {
public function a() {
$this-> ...;
// ...
}
// ...
}
and you call $some_basket->a(), behind the scenes you're actually calling something like Basket::a($some_basket). Now a() knows which Basket you want to work with. That special parameter is what this refers to: the current object you're dealing with.
short:
$this gives you access to the object variables (and methods) Edit: within the class :) Edit 2: (but not in static methods of the class) :D
Several people have explained it in similar terms, but thought I'd add that when speaking to people unfamiliar with object oriented programming, I explain that the class definition is the blueprint, as for a house, and "this" is the actual house you're working with at that moment. There might be other houses that look exactly the same, but this is the specific object (house).
A class is a template or a 'die' for an object.
Lets use the classic 'bicycle' example. There are many huffy bikes out there. However, we have created one bike, and we can use the 'this' keyword to refer to 'this' bike.
In more a more technical sense, a class is a template for an object that will be instantiated. At run time, after an object has been instantiated, or had an instance of itself created, we can then use the keyword 'this' internally to refer to the instance that runs that method.

Categories