Object Oriented Programming, extending properties - php

Ok this is not just a PHP question, but I have this problem in PHP so I will post the example in PHP.
Example:
I have three classes, say, data_abstract, person, and student. Now, I have one array of data related to each of those objects.
class person extends data_abstract
{
protected $data; //name, gender, etc
}
class student extends person
{
protected $data; //student_id, etc
}
Now, assuming each of those "data" property is from database tables, for example, table_person, table_student.
Upon instantiation, we will parse the class name by get_class() function, and get data from their related tables.
class data_abstract
{
public function __construct()
{
$name = get_class($this);
$table = 'table_' . $name;
$this->data = DB->query('SELECT * FROM ' . $table);
//whatever DB constant is,
//I'm just trying to get all rows of data from the related table.
}
}
Ok, now the problem, when I instantiate student by $student = new student(); the constructor will get data from table_student for me and put it in $student->data, but I won't be able to get the data from table_person and put those two sets of data into one object.
By extending another class, we can have all the methods (functions) extended and customized (via polymorphism), but extending the attributes/properties of each level of object seems to be hard, at least without some manual construction.
Is there any way in the abstraction level to achieve this?
(thanks for reading, wish I could've made the question clearer.)

If I understand well :
you want all your DB data in $data;
$data must be feed with data from the table 'table_classname';
$data "inherit" from $data that should have been loaded in parents class with that process.
In that case, you should externalize $data feeding so you can overload the data feeding. I edited, now we have a working example :
class DataAbstract // Using caps is much better for class name
{
public function __construct()
{
$this->loadData();
}
public function loadData()
{
// don't use getclass on $this or $this will refer to the children
$table = 'table_' . __CLASS__;
$this->data = array($table);
}
}
class Person extends DataAbstract
{
public function __construct()
{
parent::__construct();
}
public function loadData()
{
parent::loadData();
$table = 'table_' . __CLASS__;
$this->data = array_merge($this->data, array($table));
}
}
class Student extends Person
{
public function __construct()
{
parent::__construct();
}
public function loadData()
{
parent::loadData();
$table = 'table_' . __CLASS__;
$this->data = array_merge($this->data, array($table));
}
}
$c = new student();
print_r($c->data);
Outputs
Array
(
[0] => table_DataAbstract
[1] => table_Person
[2] => table_Student
)
BTW, remember that PHP got introspection, it allows you you to set the fields you need dynamically : maybe cleaner that using a big Array.
Provided you know all the fields names, you can do something like
function populate($data) // get the array from the DB
{
$fieldList = get_class_vars($this); // get the filed list
foreach ($fieldList as $key => $value)
{
$this->$key = $data[$key]; // feed the field one by one with the array
}
}

Personally, I would put the database loading class in an protected method that takes the attribute $tablename, and which loads all the data. Then in the constructor of the class call it by hand, and the parent.
class Person
{
public function __construct() {
$this - > loadData("Person");
}
}
Class Student extends Person
{
public function __construct() {
parent::__construct();
$this - > loadData("Student");
}
}
Now, when you construct Student both data from Student and Person is loaded. if you use array_merge() the 2 data arrays will be merged into one.
It's a matter of style; some people would critisise this by saying that you are now repeating something twice - more work to refactor - but I would say you are decoupling the class names and interfaces from the database design (a good thing) and with the parent call, the code is now more OO.

Related

OOP PHP with Mysql Database

If we have a code like this:
class Game {
private $_id;
private $_name;
private $_url;
public function __construct($_id,$_name,$_url){
$this->_id = $_id;
$this->_name = $_name;
$this->_url = $_url;
}
}
And we want to simply connect to our Database to get a game by id, where do we place the 'getByID' function?
Do we place it within the 'Game Class' as 'static function', do we put it in the 'Database Connection Class' as 'public function' or do we just put the method in the 'general functions inside the main index.php' as 'function'?
I currenctly have choosen for a 'static function' within the 'Game Class':
public static function getByID($id,$db){
$query = "SELECT * FROM game WHERE id = :id LIMIT 1";
$prepare = array(":id"=>$id);
$result = $db->Precute($query,$prepare);
foreach($result as $r) return new Game($r['id'],$r['name'],$r['url']);
return null;
}
(Precute is a custom function within the Database Class to prepare and execute the query)
How would you approach this?
In proper OOP, a DAL function which returns an instance of a specific class should be static within that class. As a base rule, all functionality related to one specific object should be part of that specific object, as an instance method if invoked on instances or a static method if it creates or manages instances ('factory pattern').
Your function isn't static currently, correct usage would be:
class Game
{
..other functions..
public static function getById($id)
{
..implementation, which can either access central storage or retrieve
the object itself if concurrent edits are not an issue..
}
}
Then elsewhere:
$myGame = Game::getById(684);
You may want to have a look at Doctrine instead of re-inventing the wheel. And even if you do want to make a new wheel, its code samples all follow correct OOP principles.
This Answer takes another approach. Instead of getting Objects from Static Factory. This solution takes a approach of creating a blank object and then calling the database methods to make the object a live representation of a actual row.
first the observations from your question -
an Object/Instance of Game class represents a Row of Table game. And the Game class itself can be taken as a representation of `game' table.
If the above observation is correct along with the assumption that there are more tables with a representation in class hierarchy. You should have a class to represent generic 'Table'
class Table { //The class itself can be made abstract depending upon the exact implementation
protected $_tableName;
protected $_connectionParams;
protected $idAttribute = 'id';
public function __construct($tableName, $connectionParams, $idAttribute){
$this->_connectionParams = $connectionParams;
$this->_tableName = $tableName;
if(isset($idAttribute)) {
$this->idAttribute = $idAttribute;
}
};
private function _getConnection() {
//return $db using $_connectionParams
};
public function getByID($id) {
$this->getByKeyVal($this->idAttribute, $id);
};
public function getByKeyVal($key, $val) {
$query = "SELECT * FROM ". $this->_tableName ." WHERE `". $key ."` = :key LIMIT 1";
$prepare = array(":key"=> $val);
$result = $this->_getConnection()->Precute($query,$prepare);
$this->processRow($result[0]);
};
//This needs to be overridden
public function processRow($row) {
return true;
};
}
Now extend the generic Table class for Game Table
class Game extends Table {
private $_id;
private $_name;
private $_url;
public function __construct($defaults) {
if(isset($defaults) {
if(is_array($defaults)) {
$this->processRow($defaults);
} else {
$this->getByID($defaults);
}
} else {
//Some default setup here if requried
}
$connectionParams = []; //Prepare Connection Params here
parent::__construct('game', $connectionParams);
};
//Override processRow
public function processRow($row) {
if(isset($row['id']) {
$this->_id = $row['id'];
}
$this->_name = $row['name'];
$this->_url = $row['url'];
};
}
Above is a very rough example. The actual Class structure will depend upon your requirements. But the general rule of thumb is to treat a Class as a blueprint of a concrete object. And all the methods related with a Generic Classification should go in there own class.
The getConnection Method itself can be put into a seprate DB connection class and inserted in table via a either mixin pattern or generic class inheritance.
Use the above setup like this
$game_new = new Game(); // for blank object --- for a new row
$game_435 = new Game(435); //row with 435 ID
$game_default = new Game(array( //new row with defaults
'name' => 'Some Name',
'url' => 'Some Url'
));
What you want is a "bucket" full of Game objects. When ever you want a Game Object (representing data in your database), you ask your "bucket" to give it to you. Let me give you an example of how Doctrine2 implements this:
http://docs.doctrine-project.org/en/2.0.x/reference/working-with-objects.html
So where you want to place your "getById" (or as I would do "findById"), is in your "bucket".
// lets presume that the em is an instance of \Doctrine\ORM\EntityManager
// The entity manager does what the name says.
$id = 1234;
$game = $entity_manager->find('MyNamespace\Entity\Game', $id);
$game->setName('My first game!');
// We now tell the em to prepare the object for pushing it back to the "bucket" or database
$entity_manager->persist($game);
// Now we tell the em to actually save stuff
$entity_manager->flush();
This should give you an indication of how to use it. Objects follow the Single Responsibility Principle. You don't ask an object to retrieve itself. You ask the "bucket" to retrieve you an Object.
http://en.wikipedia.org/wiki/Single_responsibility_principle
What if I told you that there are more beautiful ways to put things on their places.
A very simple case might contain 3 basic components to work:
Db framework - Which handles data access.
Table repsotor classes - Which know how to map classes to tables,
how to create classes from table data and how to create data from table classes.
Model or business layer which contain actual classes.
For better understanding imagine you have database object mapper framework.
The framework can be far complex but in few lines we can demonstrate how it`s basic
concepts work.
So the 'Framework':
<?php
//This class is for making link for db framework
class link
{
public $link;
public function __construct ($hostname, $database, $gamename, $password)
{
$this->link = new \PDO ('mysql:host='.$hostname.';dbname='.$database, $gamename, $password);
$this->link->query('use '.$database);
}
public function fetch ($query)
{
$result = $this->link->query($query)->fetch();
}
public function query ($query)
{
return $this->link->query($query);
}
public function error ()
{
return $this->link->errorInfo();
}
}
//This class collects table repositories and connections
class database
{
public $link;
public $tables = array ();
public function __construct ($link)
{
$this->link = $link;
table::$database = $this;
}
}
//This is basic table repositor class
class table
{
public static $database;
}
?>
Now as we have our db framework let us make some table repositor which knows
how to save/load/delete game:
class games extends table
{
public function create ($row)
{
$return = new game ();
$return->id = $row[0];
$return->name = $row[1];
var_export($row);
return $return;
}
public function load ($id=null)
{
if ($id==null)
{
$result = self::$database->link->fetch("select * from games");
if ($result)
{
$return = array();
foreach ($result as $row)
{
$return[$row[0]] = $this->create($row);
}
return $return;
}
}
else
{
$result = self::$database->link->fetch("select * from games where id='".$id."'");
if ($result)
{
return $this->create(reset($result));
}
else
{
echo ("no result");
}
}
}
public function save ($game)
{
if (is_array($save))
{
foreach ($save as $item) $this->save ($item);
}
if ($game->id==null)
{
return self::$database->link->query("insert into games set
name='".$game->name."'");
}
else
{
return self::$database->link->query("update games set name='".$game->name."'
where id='".$game->id."'");
}
}
public function delete ($game)
{
self::$database->link->query ("delete from games where id='".$game->id."'");
}
}
Now we can make our model which in this case will contain actuall game class.
class game
{
public $id;
public $name;
public function __construct ($name=null)
{
$this->name = $name;
}
}
And than actually use it:
$database = new database (new link('127.0.0.1', 'system_db', 'root', '1234'));
$database->tables['games'] = new games();
if (!$database->tables['games']->save (new game('Admin')))
{
var_export($database->link->error());
}
var_export($database->tables['games']->load(2));
For the moment I prefere this pattern for working with db in my projects. Using it I can achieve
that my actuall business objects(In this case class game) will know nothing about
where and how they are saved. This gives me an ability to be indipendent from
actuall storage and focus on project logics.
Also there is one lightweight framework so called db.php (http://dbphp.net) and it even
gives me ability to avoid to write table repositories and even creates/modifies tables
needed for my business classes on the fly but uses almost same concept I described here.

PHP OOP - Pass data between classes through the calling class?

I'm struggling to find a correct approach to pass data between classes, which do not directly call each other, and are only related through a parent class (which I now use, but I consider it a dirty workaround rather than anything near a solution).
I have 3 classes both able to read input and write output, and based on configuration I set one to read, another one to write. It may even be the same class, they all share a parent class, but they are always two separate instances called from a controller class.
Currently I use this sort of functionality:
class daddy {
public static $data;
}
class son extends daddy {
public function setData() {
parent::$data = "candy";
}
}
class daughter extends daddy {
public function getData() {
echo parent::$data;
}
}
while($processALineFromConfig)
$son = new son;
$son->setData();
$daughter = new daughter;
$daughter->getData();
daddy::$data = null; //reset the data, in the actual code $daughter does that in parent::
}
Instantination of these classes runs in a loop, therefore I always need to reset the data after $daughter receives them, 'cos otherwise it would stay there for another pass through the loop.
I'm absolutely sure it's not how class inheritance is supposed to be used, however I'm struggling to find a real solution. It only makes sense the data should be stored in the controller which calls these classes, not the parent, but I already use return values in the setter and getter functions, and I am not passing a variable by reference to store it there to these functions 'cos I have optional parameters there and I'm trying to keep the code clean.
What would be the correct approach to pass data through the controller then?
Thanks!
The best option would be for two object share some other, third object. This would be the class for "third object" which will ensure the exchage:
class Messenger
{
private $data;
public function store($value)
{
$this->data = $value;
}
public function fetch()
{
return $this->data;
}
}
Then a class for both instance, that will need to share some state:
class FooBar
{
private $messenger;
private $name = 'Nobody';
public function __construct($messenger, $name)
{
$this->messenger = messenger;
$this->name = $name;
}
public function setSharedParam($value)
{
$this->messenger->store($value);
}
public function getSharedParameter()
{
return $this->name . ': ' . $this->messenger->fetch();
}
}
You utilize the classes like this:
$conduit = new Messenger;
$john = new FooBar($conduit, 'Crichton');
$dominar = new FooBar($conduit, 'Rygel');
$dominar->setSharedParameter('crackers');
echo $john->getSharedParameter();
// Crichton: crackers
Basically, they both are accessing the same object. This also can be further expanded by making both instance to observe the instance of Messenger.

php prevent parent from accessing child properties

the question is simple. I have a base abstract class (person). From this i have extended another class (patients).
I save personal information (e.g. firstname, lastname) in PERSONS table [there is an ADD function. ]. Patient specific information (like illness, medicines, ...) are saved into a separate PATIENTS class. [there is an ADD function that calls the parent, then some code].
How do I prevent person's add function from accessing properties defined inside it's child, patients?
In order to make it more clear, here is a sample code:
class P {
public P_var = 'Anoush' ;
public function add ()
{
// find all properties:
foreach ($this as $prop => $val )
{
$insertables [$prop] = $val ;
}
// insert all VALUES FIELDSET etc. based on the array created above
}
class CH extends P {
public CH_var1 = 'ravan' ;
public CH_var2 = 'something' ;
}
Then when I call add, the $insertables will contain P_var, CH_var1 , CH_var2. I only want it to have P_var.
Thanks
You can do this by using Reflection (see http://www.php.net/manual/en/book.reflection.php).
class Parent {
public function add() {
$insertables = $this->_getOwnProperties(__CLASS__);
// ...
}
protected function _getOwnProperties($className) {
$reflection = new ReflectionClass($this);
$props = array();
foreach ($reflection->getProperties() as $name => $prop) {
if ($prop->class == $className) {
$props[$name] = $prop;
}
}
return $props;
}
}
However, I recommend refactoring your code instead to get a cleaner solution (e.g. add a method getProperties() (maybe defined by an interface) or whatever. Then let your database class invoke that function in order to get the list of properties to store in the database.

How to cast an array of Objects

I'm trying to cast an array of Objects for a week already in a PHP class and have had some real issues making it to work and mainly with the logic itself as I am new to classes. Looked and read a lot of resources but it does not seem to make any sense to me, any pointers would be greatly appreciated and I am open to suggestions.
The issue:
Create a PHP class as part of the project named Contact, and then a class called 'ContactList' that contains an array of these contact objects.
And next, an array of ContactList objects called 'ContactTabs'.
Then, in the program, populate one ContactList object (named 'Contacts') with the current contacts, and create a new ContactList object named 'Friends', and add some names and email addresses there for friends. It is most important that this be done in a nice, object-oriented fashion so it can allow to create other type of contacts in the future.
A 'ContactList' object, should contain not only an array that is the list of contacts, but it would also contain the text label to put on the tab. So, it is more appropriate that the ContactList be more than a simple array, but rather it should be an object that contains an array as well as a text label.
The business logic is the following:
Contact
name
bgcolor
lgcolor
email
ContactTabs
Employees
Friends
// class definition
class Contact{
// define properties
public $name;
public $bgcolor;
public $lgcolor;
public $email;
// constructor
public function __construct() {
}
//destructor
public function __destruct() {
}
}
class ContactList extends Contact {
// constructor
public function __construct($contactname,$contactbgcolor,$contactlgcolor,$contactemail) {
$this ->name = $contactname;
$this ->bgcolor = $contactbgcolor;
$this ->lgcolor = $contactlgcolor;
$this ->email = $contactemail;
parent::__construct();
}
}
$johndie = new ContactList('John Die','#FCEDC9','#FEF9ED','somecontact1#gmail.com','9');
$johndoe = new ContactList('John Doe ','#DEEDFE','#EDF5FE','somecontact2#hotmail.com,'6');
$Friends = new ExtendedArrayObject($jp);
$Employees = new ExtendedArrayObject($elvete);
$ContactTabs= new ExtendedArrayObject($Employees,$Friends);
print_r($ContactTabs);
You had the Contact class correct (although you may want to use private/protected properties for encapsulation, but you can change that later).
This is how I would do it:
class Contact{
public $name;
public $bgcolor;
public $lgcolor;
public $email;
public function __construct($name, $bgcolor, $lgcolor, $email) {
$this->name = $name;
$this->bgcolor = $bgcolor;
$this->lgcolor = $lgcolor;
$this->email = $email;
}
}
class ContactList implements Iterator, ArrayAccess {
protected $_label;
protected $_contacts = array();
public function __construct($label) {
$this->_label = $label;
}
public function getLabel() {
return $this->label;
}
public function addContact(Contact $contact) {
$this->_contacts[] = $contact;
}
public function current() {
return current($this->_contacts);
}
public function key() {
return key($this->_contacts);
}
public function next() {
return next($this->_contacts);
}
public function rewind() {
return reset($this->_contacts);
}
public function valid() {
return current($this->_contacts);
}
public function offsetGet($offset) {
return $this->_contacts[$offset];
}
public function offsetSet($offset, $data) {
if (!$data instanceof Contact)
throw new InvalidArgumentException('Only Contact objects allowed in a ContactList');
if ($offset == '') {
$this->_contacts[] = $data;
} else {
$this->_contacts[$offset] = $data;
}
}
public function offsetUnset($offset) {
unset($this->_contacts[$offset]);
}
public function offsetExists($offset) {
return isset($this->_contacts[$offset]);
}
}
And ContactTabs would be very similar to ContactList, but would accept ContactList objects instead of Contact.
How it would work is:
// create some contacts
$bob = new Contact('Bob', 'black', 'white', 'bob#bob.com');
$john = new Contact('John', 'black', 'white', 'john#john.com');
// create a contact list and add contacts to it
$contactlist = new ContactList('Contacts');
$contactlist->addContact($bob); // using a method
$contactlist[] = $john; // using array notation
// access the list by using foreach on it, since ContactList implements Iterator
foreach ($contactlist as $contact) {
echo $contact->email;
}
First step will be to throw out all that code and start fresh. I don't know what "ExtendArrayObject" is, but you don't need it for this - it only complicates things. The rest of the code is not really on the right track.
In OOP, a class is supposed to model "something." Some kind of entity, which is often, but not always, a real-world thing. The first step in OO development is to sketch out the entities involved and model them in classes. In this case, your assignment tells you exactly what the entities are:
Contact
ContactList
So, OK, what do we need to know about our contact - what properties do we need it to have? Let's say "name" and "email." Let's give it these properties then:
class Contact {
public $name;
public $email;
}
A ContactList sounds pretty simple, it's just a list of Contacts, with a title that can be displayed in a tab. I'll write it so that it stores its Contacts internally in an array:
class ContactList {
public $title;
public $contacts = array();
}
You may be wondering, why do I need a ContactList if all it does is hold a title and store Contacts in an array? The answer is, because your assignment says you need it. :) Like many aspects of OOP, their usefulness will only be revealed as your projects increase in complexity. Just go along with it for now.
Now, put these classes in 2 separate files: Contact.php and ContactList.php. (This is not strictly necessary but is generally considered best practice.) Create a 3rd file called whatever, and in it, add the following code to tie it all together:
include("Contact.php");
include("ContactList.php");
// create a Contact object
$contact = new Contact();
$contact->name = "Bill";
$contact->email = "bill#gmail.com";
// create a ContactList object
$contact_list = new ContactList();
// set its title
$contact_list->title = "My Great Contacts";
// add our contact to it
$contact_list->contacts[] = $contact;
print_r($contact_list);
With this code, you are 80% of the way there - I didn't want to do exactly what your assignment specified because that would leave nothing left for you! I encourage you to play around with this until you feel like you really "get it." It often takes a while for OOP to "click" in one's head. But it's really crucial.
Exercises:
Add some different properties to the Contact class, like "phone" and "address"
Create some more contacts and add them to the list
Create a second ContactList object, containing a different list, with different contacts in it
Extra credit: Write a method in ContactList that adds a Contact, but only if another one with the same email address doesn't already exist in the list.

A PHP design pattern for the model part [PHP Zend Framework]

I have a PHP MVC application using Zend Framework. As presented in the quickstart, I use 3 layers for the model part :
Model (business logic)
Data mapper
Table data gateway (or data access object, i.e. one class per SQL table)
The model is UML designed and totally independent of the DB.
My problem is : I can't have multiple instances of the same "instance/record".
For example : if I get, for example, the user "Chuck Norris" with id=5, this will create a new model instance wich members will be filled by the data mapper (the data mapper query the table data gateway that query the DB). Then, if I change the name to "Duck Norras", don't save it in DB right away, and re-load the same user in another variable, I have "synchronisation" problems... (different instances for the same "record")
Right now, I use the Multiton / Identity Map pattern : like Singleton, but multiple instances indexed by a key (wich is the user ID in our example). But this is complicating my developpement a lot, and my testings too.
How to do it right ?
Identity Map
Edit
In response to this comment:
If I have a "select * from X", how can I skip getting the already loaded records ?
You can't in the query itself, but you can in the logic that loads the rows into entity objects. In pseudo-code:
class Person {}
class PersonMapper {
protected $identity_map = array();
function load($row) {
if (!isset($this->identity_map[$row['id']])) {
$person = new Person();
foreach ($row as $key => $value) {
$person->$key = $value;
}
$this->identity_map[$row['id']] = $person;
}
return $this->identity_map[$row['id']];
}
}
class MappingIterator {
function __construct($resultset, $mapper) {
$this->resultset = $resultset;
$this->mapper = $mapper;
}
function next() {
$row = next($this->resultset);
if ($row) {
return $this->mapper->load($row);
}
}
}
In practice, you'd probably want your MappingIterator to implement Iterator, but I skipped it for brevity.
Keep all loaded model instances in "live model pool". When you load/query a model, first check if it has been already loaded into pool (use primary key or similar concept). If so, return the object (or a reference) from pool. This way all your references point to the same object. My terminology may be incorrect but hopefully you get the idea. Basically the pool acts as a cache between business logic and database.
Multiton
Best option if you want to use a variety of singletons in your project.
<?php
abstract class FactoryAbstract {
protected static $instances = array();
public static function getInstance() {
$className = static::getClassName();
if (!(self::$instances[$className] instanceof $className)) {
self::$instances[$className] = new $className();
}
return self::$instances[$className];
}
public static function removeInstance() {
$className = static::getClassName();
if (array_key_exists($className, self::$instances)) {
unset(self::$instances[$className]);
}
}
final protected static function getClassName() {
return get_called_class();
}
protected function __construct() { }
final protected function __clone() { }
}
abstract class Factory extends FactoryAbstract {
final public static function getInstance() {
return parent::getInstance();
}
final public static function removeInstance() {
parent::removeInstance();
}
}
// using:
class FirstProduct extends Factory {
public $a = [];
}
class SecondProduct extends FirstProduct {
}
FirstProduct::getInstance()->a[] = 1;
SecondProduct::getInstance()->a[] = 2;
FirstProduct::getInstance()->a[] = 3;
SecondProduct::getInstance()->a[] = 4;
print_r(FirstProduct::getInstance()->a);
// array(1, 3)
print_r(SecondProduct::getInstance()->a);
// array(2, 4)

Categories