I have the following class:
class cls_Tip extends cls_getTips {
public static $result = null;
public static $event = null;
public static $market = null;
public static $participant = null;
public function __construct() {
}
public static function grab( $id ) {
global $wpdb;
$query = " SELECT * FROM " . $wpdb->prefix . "asp_tips WHERE id = '" . $id . "';";
$result = $wpdb->get_row( $query );
self::$result = $result;
}
public static function add_element_to_parent_array(){
parent::add_array_ellement( self::$result );
}
public static function return_static_variable( $variable_name ) {
return self::${ $variable_name };
}
public static function get_event() {
new cls_Event;
cls_Event::grab( self::$result->markets_id );
cls_Event::add_static_variable_to_parent();
}
public static function get_market() {
new cls_Market;
cls_Market::grab( self::$result->markets_id );
cls_Market::add_static_variable_to_parent();
}
public static function get_participant() {
new cls_Participant;
cls_Participant::grab( self::$result->participants_id );
cls_Participant::add_static_variable_to_parent();
}
public static function add_static_variable( $variable_name, $class ) {
self::${ $variable_name } = $class;
}
}
When I initiate this class as follows:
new cls_Tip;
cls_Tip::get( $record->id );
cls_Tip::get_participant();
$p = cls_Tip::return_static_variable( 'participant' );
... it works, but $p continues to have the same value, after creating another 'new cls_Tip' as outlined above (in a loop.)
Is this because a static variable can only be set once? And what would you recommend doing in this case?
Thanks very much for your advice.
Best regards,
Giorgio
PS: Here is the cls_Participant class:
class cls_Participant extends cls_Tip {
public static $result = null;
public function __construct() {
}
public static function grab( $id ) {
global $wpdb;
$query = " ... ";
$result = $wpdb->get_row( $query );
self::$result = $result;
}
public static function add_static_variable_to_parent() {
parent::add_static_variable( 'participant', self::$result );
}
}
Well, you see, when you call static properties/methods of a class, unless you explicitly handle the instantiation inside of the function that you call, the "static" instance is a completely separate instance from the instantiated one -
Thus, you should do this:
$class = new cls_Tip;
$class::get( $record->id );
$class::get_participant();
$p = $class::return_static_variable( 'participant' );
And that should give you the behavior you expect...
However, in this case, you don't need to use static methods/properties... you could do:
$class = new cls_Tip;
$class->get( $record->id );
$class->get_participant();
$p = $class->return_static_variable( 'participant' );
Furthermore, this is equivalent, in your last line:
$p = cls_Tip::$participant
You don't need the getter function, since the property is public...
BUT, to further illustrate my answer, do this:
cls_Tip::$result = "Static Result";
$alt = new cls_Tip();
$alt::$result = "Instantiated Property";
echo cls_Tip::$result;
echo $alt::$result;
So, ultimately, the lesson here is that if you are going to have several separate instances of a class, you don't really need to label everything as static -
There seems to be a lot of discourse on this topic - some people say you should almost never use static methods/properties in PHP, albeit they seem to have a proper place in some cases.
However, it is my personal opinion that you would be better off taking all the static stuff out of your class, which is going to have several instances.
Thus, you would end up using the -> operator instead of the static :: operator.
A case where the :: operator would be more appropriate would be if you wanted to have a static class that managed all your instances might look like this...
class clp_Tip{
static private $instances;
//[...]
public static function new_instance($name){
return self::$instance[$name] = new $this;
}
public static function get_instances(){
return self::$instances;
}
//[...]
}
//[...]
// example:
$classOne = cls_Tip::new_instance('name');
$classTwo = cls_Tip::new_instance('two');
echo count(cls_Tip::get_instances()); // 2
$classOne->doSomeFunction();
$classOne->someProperty = "foo";
}
There are plenty of debates over why not use :: - the simplest answer is simply for design purposes, but - it makes good sense to use the operators in the way they were made to be used -
and the static operators were made to be used without having to invoke a new instance -
So, that is good enough reason, in my opinion, to remove the static stuff from your class and use the -> operator.
Related
I have a class with methods, some of these methods use the same variable across board - "$company_id". Now, I don't want to explicitly define what is contained in $company_id for every method. I want to define it once in a constructor and then reference it in my methods. Please how do I do this? This is how it looks currently.
public function __construct(){
//what should I do here?
}
public static function getItemLimit(){
$company_id = Auth::user()->company_id;
$item_limit = Company::where('id', $company_id)->count();
return $item_limit;
}
public static function currentItemCount(){
$company_id = Auth::user()->company_id;
$item_count = Item::where('company_id', $company_id)->count();
return $item_count;
}
Try this Use Company_Id instead of $abcVar
class Abc{
public static $abcVar = '';
public function __construct()
{
self::$abcVar = 11;
}
public static function getItemLimit()
{
echo self::$abcVar;
exit;
}
}
$obj = new Abc();
Abc::getItemLimit();
I am trying to make a base class ... tiny framework if you will just for practice
So I start with example of child class because it has less code !!
class User extends Base {
public $id ;
public $username ;
public $email ;
public $password ;
function __construct(){
$this->table_name = 'users';
$this->set_cols(get_class_vars('User'));
}
}
$u = new User;
$u->username = 'jason';
$u->email = 'j#gmail.com';
$u->insert();
Here is my Base class
class Base {
protected $table_name ;
protected $table_columns ;
protected function set_cols($cols){
unset($cols['table_name']);
unset($cols['table_columns']);
$this->table_columns = array_keys($cols);
}
public function insert(){
$colums = $values = array();
foreach($this->table_columns as $col )
{
if(!$this->$col) continue ;
$values[] = $this->$col ;
$colums[] = $col ;
}
$values = implode(',' , $values);
$colums = implode(',' , $colums);
echo $sql = "INSTER INTO ".$this->table_name ." ($colums)
VALUES ($values) ";
}
}
Here is the problem , I want to make filter or get method (basically reading from database) static and then return an array of objects from database data
class Base{
static function filter($conditions =array()){
$query_condition = $conditions ; // some function to convert array to sql string
$query_result = "SELECT * FROM ".$this->table_name ." WHERE $query_condition ";
$export = array();
$class = get_called_class();
foreach($query_result as $q )
{
$obj = new $class;
foreach($this->table_columns as $col )
$obj->$col = $q[$col];
$export[] = $obj;
}
return $export;
}
}
$users = User::filter(['username'=>'jason' , 'email'=>'j#gmail.com']);
Here is the problem , with filter as static function __construct in User class will not get called and table_columns, table_name will be empty
also in the filter method I can't access them anyway because they are not static ... I can make a dummy User object in the filter method and solve this problems but somehow it doesn't feel right
Basically I have a design problem any suggestion is welcomed
The problem is that the static object is not really "created" when you run statically.
If you want the constructor to run, but still in a static sort of way, you need a "singleton". This is where the object is created once and then you can re-use. You can mix this technique in a static and non-static way (as you're actually creating a "global" object that can be shared).
An example is
class Singleton {
private static $instance;
public static function getInstance() {
if (null === static::$instance) {
self::$instance = new static();
}
return self::$instance;
}
}
$obj = Singleton::getInstance();
Each time this gets the same instance and remembers state from before.
If you want to keep your code base with as few changes as possible, you can create yourself an "initialized" variable statically - you just need to remember to call it in each and every function. While it sounds great, it's even worse than a Singleton as it still remembers state AND you need to remember the init each time. You can, however, use this mixed with static and non-static calls.
class notASingletonHonest {
private static $initialized = false;
private static function initialize() {
if (!self::$initialized) {
self::$initialized = true;
// Run construction stuff...
}
}
public static function functionA() {
self::$initialize();
// Do stuff
}
public static function functionB() {
self::$initialize();
// Do other stuff
}
}
But read a bit before you settle on a structure. The first is far better than the second, but even then if you do use it, ensure that your singleton classes can genuinely be ran at any time without reliance on previous state.
Because both classes remember state, there are many code purists that warn you not to use singletons. You are essentially creating a global variable that can be manipulated without control from anywhere. (Disclaimer - I use singletons, I use a mixture of any techniques required for the job.)
Google "php Singleton" for a range of opinions and more examples or where/where not to use them.
I agree with a lot of your premises in your code and design. First - User should be a non static class. Second - Base base should have a static function that acts a factory for User objects.
Lets focus on this part of your code inside the filter method
1 $query_result = "SELECT * FROM ".$this->table_name ." WHERE $query_condition ";
2 $export = array();
3
4
5 $class = get_called_class();
6 foreach($query_result as $q )
7 {
8 $obj = new $class;
9
10 foreach($this->table_columns as $col )
11 $obj->$col = $q[$col];
12
13 $export[] = $obj;
14
15 }
The issue is that lines 1 and 10 are trying to use this and you want to know the best way to avoid it.
The first change I would make is to change protected $table_name; to const TABLE_NAME like in this comment in the php docs http://php.net/manual/en/language.oop5.constants.php#104260. If you need table_name to be a changeable variable, that is the sign of bad design. This will allow you change line 1 to:
$class = get_called_class()
$query_result = "SELECT * FROM ". $class::TABLE_NAME . "WHERE $query_condition";
To solve the problem in line 10 - I believe you have two good options.
Option 1 - Constructor:
You can rewrite your constructor to take a 2nd optional parameter that would be an array. Your constructor would then assign all the values of the array. You then rewrite your for loop (lines 6 to 15) to:
foreach($query_result as $q)
{
$export[] = new $class($q);
}
And change your constructor to:
function __construct($vals = array()){
$columns = get_class_vars('User');
$this->set_cols($columns);
foreach($columns as $col)
{
if (isset($vals[$col])) {
$this->$col = $vals[$col];
}
}
}
Option 2 - Magic __set
This would be similar to making each property public, but instead of direct access to the properties they would first run through a function you have control over.
This solution requires only adding a single function to your Base class and a small change to your current loop
public function __set($prop, $value)
{
if (property_exists($this, $prop)) {
$this->$prop = $value;
}
}
and then change line 10-11 above to:
foreach($q as $col => $val) {
$obj->$col = $val
}
Generally it is a good idea to seperate the logic of storing and retrieving the data and the structure of the data itself in two seperate classes. A 'Repository' and a 'Model'. This makes your code cleaner, and also fixes this issue.
Of course you can implement this structure in many ways, but something like this would be a great starting point:
class Repository{
private $modelClass;
public function __construct($modelClass)
{
$this->modelClass = $modelClass;
}
public function get($id)
{
// Retrieve entity by ID
$modelClass = $this->modelClass;
return new $$modelClass();
}
public function save(ModelInterface $model)
{
$data = $model->getData();
// Persist data to the database;
}
}
interface ModelInterface
{
public function getData();
}
class User implements ModelInterface;
{
public int $userId;
public string $userName;
public function getData()
{
return [
"userId" => $userId,
"userName" => $userName
];
}
}
$userRepository = new Repository('User');
$user = $userRepository->get(2);
echo $user->userName; // Prints out the username
Good luck!
I don't think there is anything inherently wrong with your approach. That said, this is the way I would do it:
final class User extends Base {
public $id ;
public $username ;
public $email ;
public $password ;
protected static $_table_name = 'users';
protected static $_table_columns;
public static function getTableColumns(){
if( !self::$_table_columns ){
//cache this on the first call
self::$_table_columns = self::_set_cols( get_class_vars('User') );
}
return self::$_table_columns;
}
public static function getTableName(){
return self::$_table_name;
}
protected static function _set_cols($cols){
unset($cols['_table_name']);
unset($cols['_table_columns']);
return array_keys($cols);
}
}
$u = new User;
$u->username = 'jason';
$u->email = 'j#gmail.com';
$u->insert();
And then the base class, we can use Late Static Binding here static instead of self.
abstract class Base {
abstract static function getTableName();
abstract static function getTableColumns();
public function insert(){
$colums = $values = array();
foreach( static::getTableColumns() as $col ){
if(!$this->$col) continue ;
$values[] = $this->$col ;
$colums[] = $col ;
}
$values = implode(',' , $values);
$colums = implode(',' , $colums);
echo $sql = "INSERT INTO ". static::getTableName() ." ($colums) VALUES ($values) ";
}
static function filter($conditions =array()){
$query_condition = $conditions ; // some function to convert array to sql string
$query_result = "SELECT * FROM ".static::getTableName() ." WHERE $query_condition ";
$export = array();
$columns = static::getTableColumns(); //no need to call this in the loop
$class = get_called_class();
foreach($query_result as $q ){
$obj = new $class;
foreach( $columns as $col ){
$obj->$col = $q[$col];
}
$export[] = $obj;
}
return $export;
}
}
Now on the surface this seems trivial but consider this:
class User extends Base {
public $id ;
public $username ;
public $email ;
public $password ;
final public static function getTableName(){
return 'users';
}
final public static function getTableColumns(){
return [
'id',
'username',
'email',
'password'
];
}
}
Here we have a completely different implementation of those methods from the first Users class. So what we have done is force implementation of these values in the child classes where it belongs.
Also, by using methods instead of properties we have a place to put custom logic for those values. This can be as simple as returning an array or getting the defined properties and filtering a few of them out. We can also access them outside of the class ( proper like ) if we need them for some other reason.
So overall you weren't that far off, you just needed to use static Late Static Binding, and methods instead of properties.
http://php.net/manual/en/language.oop5.late-static-bindings.php
-Notes-
you also spelled Insert wrong INSTER.
I also put _ in front of protected / private stuff, just something I like to do.
final is optional but you may want to use static instead of self if you intend to extend the child class further.
the filter method, needs some work yet as you have some array to string conversion there and what not.
How can I figure out in what class a reference to a variable was initiated (and currently exists)?
Example:
<?php
class MyClass {
public $array = array(
"this",
"is",
"an",
"array"
);
}
$class = new MyClass();
$arrayReference = &$class->array;
GetClassForVariable($arrayReference); //Should return "MyClass"
?>
My best bet is some kind of Reflection, but I haven't found any functions that seem suitable for this.
Edit:
A better suited example for what I want is the following:
<?php
class API_Module {
public $module;
public $name;
private $methods = array();
public function __construct($module, $name) {
$this->module = $module;
$this->name = $name;
$this->methods["login"] = new API_Method($this, "login", "Login");
}
public function GetMethod($method) {
return $this->methods[$method];
}
public function GetURL() {
return $this->module; //Should return "session"
}
}
class API_Method {
public $method;
public $name;
private $parentReference;
private $variables = array();
public function __construct(&$parentReference, $method, $name) {
$this->parentReference = $parentReference;
$this->method = $method;
$this->name = $name;
$this->variables["myvar"] = new API_Variable($this, "myvar");
}
public function GetURL() {
return $this->GetParentURL() . "/" . $this->method; //Should return "session/login"
}
public function GetVariable($variableName) {
return $this->variables[$variableName];
}
private function GetParentURL() {
// Need to reference the class parent here
return $this->parentReference->GetURL();
}
}
class API_Variable {
public $name;
private $parentReference;
public function __construct(&$parentReference, $name) {
$this->parentReference = $parentReference;
$this->name = $name;
}
public function GetURL() {
return $this->GetParentURL() . "/" . $this->name; //Should return "session/login/myvar"
}
private function GetParentURL() {
// Need to reference the class parent here
return $this->parentReference->GetURL();
}
}
$sessionModule = new API_Module("session", "Session");
var_dump($sessionModule->GetMethod("login")->GetVariable("myvar")->GetURL()); //Should return "session/login/myvar"
?>
Now, this works fine, but I'd love to be able to do this without using $parentReference in every single subvariable. It might not be possible, but I'd love to know whether it is or not.
For your example:
$class = new MyClass();
$arrayReference = &$class->array;
GetClassForVariable($arrayReference); //Should return "MyClass"
to find out to which variable originally the alias $arrayReference refers to is not possible in PHP. There is no function available resolving the aliases.
Additionally $class->array is just a variable on it's own. So you would also need to find out based on a value in which class it was defined. That is not possible as well, similar to that PHP does not offer anything to resolve a variable alias, it also does not offer anything to learn about the definition of a variable.
So in short PHP does not have a ReflectionVariable class available ;) I wonder if it is even possible.
The get_class() function should work:
http://php.net/manual/en/function.get-class.php
I agree with GRoNGoR that you shouldn't need to get the parent class of a property of an instantiated object. You could instead just get the name of the class before accessing the property. For example:
$class = new MyClass();
$parent_class = get_class($class); // returns "MyClass"
$arrayReference = &$class->array;
Not sure why you'd need the parent class of the property when you have the object instance and can easily get the parent class from there.
My brain is running out of power and with it my skill to search (I didn't find an 100% answer to what I'm looking for). That being said, I have a class inside which is an empty static variable $title which I'd need to define inside __construct, but it can't seem to get it via global. Let's just show some code, shall we?
$arg = array( my data is here );
class Article
{
static $title;
public function __construct()
{
global $arg;
self::$title = $arg['title'];
}
public static function title()
{
return self::$title;
}
}
My end goal would be to simply do
echo Article::title();
to get the title of the article. But as I previously mentioned, I have no such luck. All help is appreciated.
Although I agree with #Amber's comments, you can do what you are trying to do, but you cannot use the constructor for that as you are not necessarily instantiating an object:
$arg = array( my data is here );
class Article
{
static $title;
static function set_static()
{
global $arg;
self::$title = $arg['title'];
}
public static function title()
{
return self::$title;
}
}
Article::set_static();
I would also pass the value as an argument, but that does not change the way it works.
Use Singleton
$arg = array("title"=>" my data is here ");
class Article
{
static $title;
static $instance = null ;
public function __construct()
{
self::$title = $GLOBALS['arg']['title'];
}
public static function getInstance()
{
if(self::$instance === null)
{
self::$instance = new self();
}
return self::$instance;
}
public static function title()
{
self::getInstance();
return self::$title;
}
}
var_dump(Article::title()); //Returns string ' my data is here ' (length=17)
var_dump(Article::getInstance()->title()); // Returns string ' my data is here ' (length=17)
You should initialize it in the first place.
Static $title = ...
The method --construct is called when you new an instance.
I use a static function, and for inefficient variable loads I have it access a private or protected member, as follows:
$arg = array('title' => 'My Title');
class Article
{
static function title()
{
global $arg;
return $arg['title'];
}
// or if the var load is inefficient ...
protected static $title_md5;
static function title_md5()
{
if (!isset(self::$title_md5))
self::$title_md5 = md5(self::title());
return self::$title_md5;
}
}
echo(
'title = ' . Article::title() . "\n" .
'title_md5 = ' . Article::title_md5() . "\n"
);
Outputs:
title = My Title
title_md5 = 5badc643b79fdda9775c45b46540afc0
i'm quite new to php and trying to learn. I have 2 similiar classes. I want to create that objects when i pass count and object type. I read some about factory pattern. Here is my factory class:
class AssetFactory
{
private static $table;
public static $objects = array();
public static function Create($asset,$count)
{
switch ($asset) {
case "Item":
self::$table = "items";
break;
case "Job":
self::$table = "jobs";
break;
}
$db = new Database();
$rows = $db->query("SELECT * FROM ".self::$table." LIMIT ".$count);
foreach($rows as $row)
{
self::$objects[] = new $asset($row);
}
return self::$objects;
}
}
and when i need 5 items i use:
$myItems = AssetFactory::Create('Item',5);
when i need some jobs i use:
$myJobs= AssetFactory::Create('Job',5);
item and job are that similiar classes. My question is here, as i said im trying to learn. Am i doing this right? Did i understand factory pattern right? Have any good documents about this(i read everything on php.net, got anything else).
There are few thing that seem wrong in this case.
First of all , there are two similar structures which are used for object creation:
factories: if object requires some sort of initialization before released for 'consumption'
builders: if before creating object you have to create bunch of other objects
Usually people do not distinguish between the two, and just call them "Factories". So these would be two case where you use a factory.
What you have right now does not fit the description. You are creating some sort of database connection, then getting some data, and then using it for creating a list of objects. This is not a reusable code.
It would be much better if the usage of factory would be something like this :
$connection = new PDO( .. blah.. );
$stmt = $connection->query( 'SELECT * FROM '.$type.' LIMIT '.$count );
$factory = new Factory;
$collection = $factory->buildCollection( $type, $stmt->fetchALL(PDO::FETCH_ASSOC) );
Of course, with factory class which implements this behavior.
Additionally , you might want to watch (assuming, that you haven't seen already) two videos on the subject:
Don't Look For Things!
Unit Testing
Global State and Singletons
I am far from an authority on the factory design pattern, but I usually delegate the instantiation to a subclass.
<?php
class AssetFactory
{
public static function Create($asset, $count)
{
$objects = false;
switch ( strtolower($asset) ) {
case 'item':
case 'job':
$class_name = 'Asset'.$asset;
$asset_obj = $class_name::getInstance();
$objects = $asset_obj->Create($count);
break;
default:
// Invalid asset
break;
}
return $objects;
}
}
class Asset
{
var $name = null;
var $table = null;
private static $instance = null;
private function __construct() {}
private function __clone() {}
public function Create($count)
{
$objects = array();
$db = new Database();
$rows = $db->query("SELECT * FROM ".$this->table." LIMIT ".$count);
if ( is_array($rows) ) {
foreach($rows as $row)
{
$objects[] = new Item($row);
}
}
return $objects;
}
public static function getInstance()
{
if ( empty($self::$instance) ) {
$class_name = __CLASS__;
self::$instance = new $class_name();
}
return self::$instance;
}
}
class AssetItem extends Asset
{
private function __construct()
{
$this->name = 'Item';
$this->table = 'item';
parent::__construct();
}
}
class AssetJob extends Asset
{
private function __construct()
{
$this->name = 'Job';
$this->table = 'job';
parent::__construct();
}
}