Hey, everyone. I couldn't find anything Googling this problem, and I've found really good answers to some questions on SO before, so I'm taking this excuse to join the community.
I'm creating a hierarchy of classes for a PHP project I'm working on, and I'd like to have some variables in the classes initialized within the constructor function without explicitly writing the initialization code. Specifically I want to have the interpreter assume that some of the variables are actually pointers to a certain class. If I could do something like C structs, that would be pretty close to what I want.
So far, the only thing I came up with is to explicitly state the variable type within its own name and have the class call an initializing function on each, like;
class A{
...
}
class B{
var $x_A;
function initVar($var){
list($varname, $vartype) = split('_',$var);
$this->$var = new $vartype();
}
}
And B's constructor calls initVar on all of its get_class_vars(get_class($this)), so anything that inherits from it will do initialization in the same way; obviously including a check on the variable name, a check that the class exists, and a better separation scheme than a single underscore. I just cannot help but think that there is a better way to do this that isn't hardcoding the initialization into the construction function.
If anyone knows of a better way to do this, your help would be much appreciated.
Your method there would probably work, however it could get very tiresome to actually use it. For example, imagine having to reference those variables all the time:
$myObject->account_ServiceAccountType
If you really wanted to go with something like this, perhaps a mapping variable might be useful:
class B {
public $x, $account;
private $map = array(
'x' => 'A',
'account' => 'ServiceAccountType'
);
public function __construct() {
foreach ($this->map as $var => $class) {
$this->$var = new $class;
}
}
}
You could also try this method out. It uses PHP's magic __get function.
class B {
private $map = array(
'x' => 'A',
'account' => 'ServiceAccountType'
);
private $vars;
public function __construct() {
$this->vars = array();
foreach ($this->map as $var => $class) {
$this->vars[$var] = new $class;
}
}
public function __get($v) {
return $this->vars[$v];
}
}
Notice that you don't need to define the class members twice using this method.
Related
This is an odd situation and I think the answer is 'you can't do that, what are you thinking?' but hope someone can prove me wrong.
My goal is to store a globally scoped function in a variable then inject it for execution within a class object.
I would like to avoid using call_user_func() as this searches for the function in the global namespace and is the same effect as if I were to just execute the global function from within the class object. I would like my class to execute the object as if it were an internal class method, not an external function. This comes close but not quite.
I cannot modify the function or wrap it in a class.
(Why am I jumping through these hoops?) Needs to be used within this class to follow a spec.
I know I can just duplicate the function in the class and be done with it, but you know the issues with that (plus it creeps up on SRP.) Reflection would work perfectly but this function is not in a class, it is just out there in an include. I've tried wrapping it an anonymous function and the closure object doesn't execute the function.
Is there any hope to do this? The function is simple, accepts a scalar param, does some stuff to it, returns a value (and is tightly coupled with other code, cannot be moved or changed.)
function someFunction($param)
{
// do some stuff
return $someScalarValue;
}
What I would hope is something like
$func = someFunction([some value]); // doesn't work of course, this would store result in $func
$cls = new SomeClass($func);
Then a method in the class could run the function object, much like call_user_func but not have to search the global namespace.
protected function someThing()
{
$this->injected_function([some class value]); // also doesn't work of course
}
When you use $this you are in the objects instance scope. You could pass a (reference) method into the constructor.
$myFunc = function($arg) { var_dump($arg); return 314; };
class myClass {
private $func;
public function __construct($func) {
$this->func = $func;
}
public function do($value) {
$this->func->call($this, $value);
}
}
$var = 'Hello world!';
$myObj = new myClass($myFunc);
$value = $myObj->do($var); // $value is now 314
If you do not want the function to be stored in global namespace you can just pass even an anonymous function like this on the fly:
$myObj = new myClass(function($arg) { var_dump($arg); return 314; });
$value = $myObj->do($var); // $value is now 314
Thank you #Markkus Zeller for your comments, as I suspected there is no way to do what I originally was tasked, to "inject" a global function as an dependency. There is, but it only really works with anonymous functions.
After a lot of stressful pushback, I convinced our managers that wrapping this in a simple class was the way to go. This,
// require_once('some-function.php');
function someFunction($param)
{
// do some stuff
return $someScalarValue;
}
. . . now becomes this. (Typed out on the fly and may contain deficiencies, concept only)
// require_once('some-function.php');
require_once('path/to/SomeFunctionClass.php');
function someFunction($param)
{
$cls = new SomeFunctionClass($param);
return $cls->execute();
}
. . . where execute() contains identical code that was in someFunction(). I can now use "SomeFunctionClass" for a DI. There is more to the story, but that is the gist, and this one change can be implemented without modifying any of the 450 or so instances that use this global function (and each of those they can be gradually ported to use the new wrapper.) It also allows me to isolate and mock the functionality for unit testing.
Second update
I think I've been approaching this problem from the wrong side of the coin. Would I be correct in assuming that I should be making 'First' an abstract class and just finding a way to reference 'Second' and 'Third' at a later time?
Update
Based on some of the feedback, I have added some content to try and clear up what I would like to do. Something similar to this effect.
I know from just looking at the code below that, it is a waste of performance "if" it did work and because it doesn't, know I am approaching the problem from the wrong angle.The end objective isn't all to uncommon at a guess from some of the frameworks I've used.
I'm more trying to base this particular bit of code on the CodeIgniter approach where you can define (what below) is STR_CLASS_NAME in a config file and then at any point through the operation of the program, use it as i have dictated.
STR_CLASS_NAME = 'Second';
class First {
protected $intTestOne = 100;
public function __construct() {
$strClassName = STR_CLASS_NAME;
return new $strClassName();
}
public function TestOne() {
echo $this->intTestOne;
}
protected function TestThreePart() {
return '*Drum ';
}
}
class Second extends First{
/* Override value to know it's working */
protected $intTestOne = 200;
/* Overriding construct to avoid infinite loop */
public function __construct() {}
public function TestTwo() {
echo 'Using method from extended class';
}
public function TestThree() {
echo $this->TestThreePart().'roll*';
}
}
$Test = new First();
$Test->TestOne(); <-- Should echo 200.
$Test->TestTwo(); <-- Should echo 'Using method from extended class'
$Test->TestThree(); <-- Should echo '*Drum roll*'
You may be asking, why do this and not just instantiate Second, well, there are cases when it is slightly different:
STR_CLASS_NAME = 'Third';
class Third extends First{
/* Override value to know it's working */
protected $intTestOne = 300;
/* Overriding construct to avoid infinite loop */
public function __construct() {}
public function TestTwo() {
echo 'Using method from extended class';
}
public function TestThree() {
echo $this->TestThreePart().'snare*';
}
}
$Test = new First();
$Test->TestOne(); <-- Should echo 300.
$Test->TestTwo(); <-- Should echo 'Using method from extended class'
$Test->TestThree(); <-- Should echo '*Drum snare*'
Situation
I have a an abstract class which extends a base class with the actually implementation; in this case a basic DB wrapper.
class DBConnector ()
class DBConnectorMySQLi extends DBConnector()
As you can see, MySQLi is the implementation. Now, dependant upon a value in the configuration process, a constant becomes the class name I wish to use which in this case (as shown below builds DBConnectorMySQLi.
define('STR_DB_INTERFACE', 'MySQLi');
define('DB_CLASS', 'DBConnector'.STR_DB_INTERFACE);
Objective
To have a base class that can be extended to include the implementation
For the code itself not to need know what the name of the implementation actually is
To (in this case) be able to type or use a project accepted common variable to create DBConnectorMySQLi. I.E. $db or something similar. W
Issue
When it comes to actually calling this class, I would like the code to be shown as below. I was wondering whether this is at all possible without the need to add any extra syntax. On a side note, this constant is 100% guaranteed to be defined.
$DBI = new DB_CLASS();
Solution 1
I know it is possible to use a reflection class ( as discussed in THIS QUESTION) and this works via:
$DBI = new ReflectionClass(DB_CLASS);
However, this creates code that is "dirtier" than intended
Solution 2
Start the specific implementation of DBConnectorMySQLi within the constructor function of DBConnector.
define('STR_DB_INTERFACE', 'MySQLi');
define('DB_CLASS', 'DBConnector'.STR_DB_INTERFACE);
class DBConnector() { public function __construct() { $this->objInterface = new DBConnectorMySQLi(); }
class DBConnectorMySQLi()
This however would result in the need to keep on "pushing" variables from one to the other
Any advice is much appreciate
You can use variables when you instantiate a class.
$classname = DB_CLASS;
$DBI = new $classname();
Source: instantiate a class from a variable in PHP?
I'm working on a class which needs to be accessible via static function calls as well as object methods. One thing I have found is that I'm duplicating logic across multiple functions.
Simplified example:
class Configurable{
protected $configurations = array();
protected static $static_configurations = array();
public function configure($name, $value){
// ...lots of validation logic...
$this->configurations[$name] = $value;
}
public static function static_configure($name, $value){
// ...lots of validation logic (repeated)...
self::$static_configurations[$name] = $value;
}
}
I've found a solution to this, but it feels really dirty:
class Configurable{
protected $configurations = array();
protected static $static_configurations = array();
public function configure($name, $value){
// ...lots of validation logic...
if (isset($this)){
$this->configurations[$name] = $value;
}
else{
self::$static_configurations[$name] = $value;
}
}
}
I need the static function as well so that I can set configurations throughout the application. Also, the nice thing with this technique is that I can use the same method names in both scopes.
Are there any problems with testing scope like this? Performance issues, forward compatibility issues, etc. It all works for me on PHP 5.2, and I don't need to support <5.
The issue with the second method is that it will result in an error when error reporting is set to E_STRICT. For example:
Strict standards: Non-static method Foo::bar() should not be called statically in /home/yacoby/dev/php/test.php on line 10
A point with PHP6 is that the E_STRICT errors are moved to E_ALL. In other words E_ALL will cover all errors including not allowing you to call non static methods statically.
An alternative method may be to move the validation logic to a static function. That way the non static function and the static function can call the validation logic.
Static methods would require a different number of arguments than their objective counterpart - the additional argument would be an execution context. If there's no execution context, then it only makes sense to call it statically.
My preferred approach given that I'm building a library with multiple interfaces like this, is to create a static class and a dynamic class. Have one proxy the calls to the other. For example:
class DynamicClass {
protected $foo;
protected $bar;
public function baz($arg1) {
return StaticClass::bar($this->foo, $arg1);
}
public function zop($arg1, $arg2) {
return StaticClass::zop($this->foo, $this->bar, $arg1, $arg2);
}
// Context-less helper function
public function womp($arg1) {
return StaticClass::womp($arg1);
}
}
class StaticClass {
public static function baz(&$fooContext, $arg1) { ... }
public static function zop(&$fooContext, &$barContext, $arg1, $arg2) { ... }
public static function womp($arg1) { ... }
}
It's up to you exactly how you pass context to the static class - you'll have to do whatever makes sense for you. The work done in most functions should be pretty minor (if you're doing a lot, then you probably should be breaking the work up into smaller functions as a rule), and so should only require a handful of context arguments. Or you could create a full context array and pass that around everywhere (either populating it in DynamicClass just before each call, or else track all DynamicClass properties in that array so you can quickly & easily pass it around.
Though actually it looks like you might benefit from a Singleton design pattern. From what I can see, you're trying to create a global Configurable, and also have the option to create individual local Configurables. With the singleton design pattern, you create a globally accessible version of a class that you can guarantee you only have one of (without breaking OOP design principles and having to rely on $_GLOBALS etc). For example:
class DynamicClass {
protected $foo;
protected $bar;
public function baz($arg1) { ... }
public function zop($arg1, $arg2) { ... }
public static function getSingleton() {
static $instance = null;
if ($instance === null) $instance = new DynamicClass();
return $instance;
}
}
No matter where in your code you are, you can get access to the same instance with DynamicClass::getSingleton(). You also have the option of creating one-off non-singleton versions. You essentially get the best of both worlds while only having to write all your methods with dynamic access in mind exclusively.
I don't find it so absurd to allow calling a method on an instance and statically as well. My case:
TestRecord::generateForm(); // Generate an empty form.
$test = new TestRecord( $primaryKey );
[...]
$test->generateForm(); // Generate an edit form with actual $test values.
Static side of my class deals with blank/new logics,
while instance side means live data are used.
PHP 5.3 allows to achieve this by using __call, __callStatic and static:: :
public function __call( $name, $args )
{
if ( $name == 'generateForm' ) {
$this->fields = static::createFields(); // Action 1 : static.
$this->fillFields(); // Action 2 : instance.
static::renderForm( $this->fields ); // Action 3 : static.
}
}
public static function __callStatic( $name, $args )
{
if ( $name == 'generateForm' ) {
$fields = static::createFields(); // Action 1 : static.
// Action 2 : none.
static::renderForm( $fields ); // Action 3 : static.
}
}
Note: The static:: late binding qualifier is used because my 3 action methods (createFields, fillFields and rendreForm) are implemented as protected in the subclasses of this one, which is abstract. This is possible because PHP let protected members be accessed in both directions: from base to subclass, but from subclass to superclass as well. Which is different from other OO languages, as far as I know.
as in core php we use index.php?var=, so to do the same thing in oop php what should we use.
Say you have two classes, A and B. Is it possible to instantiate both classes once and then let class B call methods in class A, and vice versa?
It can be done using double colon (::) ... ... but then the method becomes static - is that a disadvantage? (see example below)
Can it be done in other ways? With interfaces?
This code shows what I try to do:
class A {
function horse() {
echo "horse";
}
}
class B {
function jump() {
// $A = new A; ... don't want to add this in each method.
$A->horse(); // Fails - $A is out of scope ($A = new A;).
// A::horse(); // Old code style - works.
// $this->horse(); // Works if you extend A - not self-documenting.
// $this->A->horse(); // Fails - out of scope.
}
}
$A = new A;
$B = new B; // Better to use "$B = new B($A);" ?
$B->jump(); // fails - the horse is sleeping.
Edit
Well, I am building a MVC-framework and I want to re-use code from other classes.
Some real-world examples:
a database object that is being passed across classes.
a "url" class that creates/manipulates URLs - used by other classes.
... and a code example:
class url {
function anchor($url,$name) {
return "{$name}";
}
}
class someclass {
function text($str,$url) {
return "{$str}. " . $url->anchor($url,"Read more...");
}
}
I think what you are asking for is multiple inheritance where you could extend both A and B like this
<?php
class C extends A,B {
//...
}
This however is not possible in PHP for good reasons(it actually is creating more problems than it's trying to solve).
Now you might ask yourself if there is any alternative to multiple inheritance and the answer is: Yes, there is! Have a look at the strategy pattern(as Benjamin Ortuzar also has pointed out).
UPDATE:
I just read your question a second time and figured that you might be looking for the singleton pattern, which lets you instantiate an instance of an class only once like this:
class A
{
protected static $_instance;
protected function __construct() //prohibit creating instances from outside
{ }
public static function getInstance()
{
if( self::$_instance === NULL ) {
self::$_instance = new self();
}
return self::$_instance;
}
}
$instance = A::getInstance();
Now A::getInstance() always returns the same instance of A which you can use in B and you can have both the advantages of dynamic functions and the accessibility of static functions.
UPDATE2:
Your database belongs into a registry if you can have more than one db-connection. If you're absolutely certain that you will always need only one db-connection you could as well make it a singleton.
For the URL helper I'd suggest writing a static class if you can and if you really need it to be dynamic make it a singleton, as mentioned before.
I think that this should work:
$B = new B();
$B->jump();
But you should read/refer to http://www.php.net/manual/en/language.oop5.php
Of course you should import the class if you're accessing it from a different php file. And if you're in the object you're calling the method of you should use
$this->jump();
I would suggest reading about the factory and strategy pattern. You can read more about this from chapter one of this fantastic book. link text
I would recomend you reading the whole book.
Maybe (just guessing) you're looking for something like aggregation in COM:
Aggregation is the object reuse mechanism in which the outer object exposes interfaces from the inner object as if they were implemented on the outer object itself.
You can build something like that with the "magic method" __call. Each time a method is called that isn't callable in the object's context this method is invoked and your code can decide what to do with this call. E.g. it can test if another object that is stored as a property of the "outer" object exposes a method with that name and than call that inner object's method.
class Foo {
protected $inner = null;
public function __construct($inner=null) {
if ( is_null($inner) && !is_object($inner) ) {
throw new Exception('...');
}
$this->inner = $inner;
}
public function __call($name, $arguments) {
// also check http://uk.php.net/is_callable
if ( !is_null($this->inner) && method_exists($this->inner, $name) ) {
return call_user_func_array( array($this->inner, $name), $arguments);
}
else {
// add some error handler here
throw new Exception('...');
}
}
function jump() {
$this->horse();
echo " jumps";
}
}
class Bar {
function horse() {
echo "horse";
}
}
$foo = new Foo(new Bar);
$foo->jump();
This works. But I'd recommend something like that only for quite specific circumstances. The most obvious reason beeing that it's hard to tell from the outside what this object $foo really can and cannot do.
Is there a way in PHP to find out what object called what method in another object.
Exmaple:
class Foo
{
public function __construct()
{
$bar = new Bar();
$bar->test();
}
}
class Bar
{
public function test()
{
}
}
$foo = new Foo();
Would there be a way for me to find out that the test method was called from the foo object?
you could use debug_backtrace, a bit like this :
BTW, take a look at the comments on the manual page : there are some useful functions and advices given ;-)
class Foo
{
public function __construct()
{
$bar = new Bar();
$bar->test();
}
}
class Bar
{
public function test()
{
$trace = debug_backtrace();
if (isset($trace[1])) {
// $trace[0] is ourself
// $trace[1] is our caller
// and so on...
var_dump($trace[1]);
echo "called by {$trace[1]['class']} :: {$trace[1]['function']}";
}
}
}
$foo = new Foo();
The var_dump would output :
array
'file' => string '/home/squale/developpement/tests/temp/temp.php' (length=46)
'line' => int 29
'function' => string '__construct' (length=11)
'class' => string 'Foo' (length=3)
'object' =>
object(Foo)[1]
'type' => string '->' (length=2)
'args' =>
array
empty
and the echo :
called by Foo :: __construct
But, as nice as it might look like, I am not sure it should be used as a "normal thing" in your application... Seems odd, actually : with a good design, a method should not need to know what called it, in my opinion.
Here is one liner solution
list(, $caller) = debug_backtrace(false, 2);
As of PHP7 this won't work based on the docs: http://php.net/manual/en/function.list.php as we cannot have empty properties, here is a small update:
list($childClass, $caller) = debug_backtrace(false, 2);
You could also have the calling object pass itself as an argument
e.g.
class Foo
{
public function __construct()
{
$bar = new Bar();
$bar->test($this);
}
}
class Bar
{
public function test()
{
}
}
$foo = new Foo();
I got this idea from the book "Design Patterns: elements of reusable object-oriented software" by Erich Gamma, et al, on page 278 in the discussion on the "Mediator" structural pattern.
The point of the pattern is to reduce the number of many-to-many connections between a bunch of objects/classes. You create a mediator class that all those classes treat as a hub. That way the classes don't need to know about each other. The mediator handles the interactions. For the mediator to be informed of changes in the classes it tracks, they can pass themselves as arguments, or the mediator can be implemented using the "Observer" pattern.
2018 EDIT:
I sometimes use interfaces with the above code, like this:
interface someInterface // many classes may implement this interface
{
public function giveMeBar();
}
class Foo implements someInterface
{
public function __construct()
{
$bar = new Bar();
$bar->test($this);
}
public function giveMeBar() {
return 'Bar';
}
}
class Bar
{
public function test(someInterface $a)
{
echo $a->giveMeBar();
}
}
$foo = new Foo(); // prints "Bar"
You can probably achieve this with a debug backtrace, though this seems kind of hackish.
Your alternative option is to pass a parameter to that class and tell it where it is being called from, when you instantiate the class from within another.
At the very least, you could use debug_backtrace and analyze that to find the calling method.
I think you should also be able to do it using the reflection API, but it's been too long since I've used PHP and I don't remember exactly how. The links should at least get you started, however.
#Pascal MARTIN:
Yes, in normal applicacions it's probably not needed. But sometimes it could be useful.
Consider an example from my own app:
There's a Controller subclass which can use a Template object to prepare its output. Every template has a name to refer it to. When a Controller needs a Template, it asks the TemplateManager for it by giving that name as a parameter.
But there could be many template files with that name for different Controllers. Controlers are used as plugins, and may be written by different users, so the names used by them can't be controlled to no collide with each other. Namespaces for templates are needed.
So TemplateManager, which is a factory for Template objects, needs the template name and the namespace name to locate the proper template source file. This namespace is related to the particular Controller's class name.
But, in most cases, each Controller will be using templates from its own namespace and only in rare cases from other namespaces. So specifying the namespace in each call to TemplateManager::getTemplate() each time would be a mess. It's better if namespace is optional and defaults to... the Controller which calls the TemplateManager::getTemplate()! And here's a good place for knowing the caller.
Of course the caller Controller could pass itself or its name as a parameter, but it doesn't really differ much from passing the namespace name. It couldn't be optional in either way.
But if you can know the caller, you can use that information to default the namespace automatically inside the getTemplate(), without even bothering the caller. It doesn't have to know how getTemplate() is handling it in its inside and how does it know the proper default namespace. He only needs to know that it does, and that it can pass any other namespace optionally if it really needs to.
This function does the job without debug_backtrace :
/*
usage :
some code...
getRealCallClass(__FUNCTION__);
some code...
*/
function getRealCallClass($functionName) //Parameter value must always be __FUNCTION__
{
try
{
throw new exception();
}
catch(exception $e)
{
$trace = $e->getTrace();
$bInfunction = false;
foreach($trace as $trace_piece)
{
if ($trace_piece['function'] == $functionName)
{
if (!$bInfunction)
$bInfunction = true;
}
elseif($bInfunction) //found !!!
{
return $trace_piece['class'];
}
}
}
}
var_dump(getClass($this));
Used in a method in namespace B this will give you the class that called a method in namespace B from namespace A.