php fetch_object inheritance - php

I have class:
class item{
public id='';
public name='';
}
inside this class i want to have a function that fills up class with values from mysql query
like this:
$result_item = $this->mysqli->query("SELECT *
FROM items
WHERE item_id=".$item_id."
LIMIT 1");
$res = $result_item->fetch_object(SalesOrderItem);
$this = $res;
this code doesnt work, but is there a way to do this?

You need to look at the documentation around the mysqli::fetch_object.
Your class name needs to be specified as a string like so:
$result_item->fetch_object('SalesOrderItem'); // or 'item' your question is inconsistent here
You also may need to pass some values to the constructor to help you along. I would strongly recommend reading through the user notes on the documentation page - http://us3.php.net/manual/en/mysqli-result.fetch-object.php for some better examples of usage than given in the main documentation itself.
The fatal error you mention in your comments is because you can't change $this. That is an internal reference to the current object instance. Trying to change it make no sense.
If you intent is you have an object class that is, in essence, its own object relational mapper (ORM). To where it makes a call to the database, populates properties from records and somehow mutates itself into another class, this is not really possible. What you probably need to look to do is utilize a factory pattern of sorts to have a class that does nothing but instantiate classes of given type using the ORM approach.
So maybe usage would be like this:
// The class with MySQLi logic could be called something like MysqlObjectfactory
// It could take input like an instantiated mysqli object, DB table name,
// the class name you are trying to map to, and the id for the specific item in the class you are looking for
// it would use the logic noted above to generate an object with the specifications given
// and return it to the caller
$object = MysqliObjectFactory::getObject($mysqli, $db_table, $class_name, $id);
The other thought that jump to my mind is: why reinvent the wheel? It sounds like what you are looking for is an object relational mapper. There are several of these for PHP that are really widely used: Doctrine, Propel, PHP Active Record, etc. You might check these out as they will give you a lot more functionalitu/flexibility than trying to do this with mysqli::fetch_object() where the mapping depends on the database field (or provided alias in SQL) exactly matching the class property names (that is without having to do mapping in class constructor).

Related

CRUD and OOD. How to approach this?

Please be brutally honest, and tear my work apart if you have to.
So I'm re-writing a small web-application that I recently made. The reason for this is simply that the code got pretty messy and I want to learn and apply better OO design. What this application should do is just simple CRUD.
I have a database with 3 tables, companies and partners which are in no relation to each other and city which has a 1:n relation with companies and partners. Very simple, really. Now, I have several questions which i will state at the end of my post. Here i'll just try to explain:
My first approach was that I created classes company, partner and city, fetched all datasets from the database and created objects from that:
class company {
private $id = null;
private $name = null;
private $city = null;
//many more attributes
function __construct( $id, $name, $city, [...] ) {
$this->id = $id;
$this->name = $name;
$this->city = $city;
//huge constructor
}
/*
* getters + setters here
*
* no need to paste the partner class as it looks just like this one
*
*/
}
And that is all these classes did. I fetched every dataset from the database and constructed company, partner and city objects (the attribute city within these classes is an object with several attributes itself) and saved them into two arrays arr_companies and arr_partners, which then held these objects...and it worked fine like that.
Now, what I wanted is to update, insert, delete into the database, and all 3 classes (city, company, partner) need this functionality. My approach was that I created a new class with a constructor that would basically take 2 strings command and object, e.g. ('update', 'company') and it would then update the company directly in the database leaving my objects untouched. That made me really sad, because I had such nicely constructed objects and I didn't know how to make use of them.
Questions:
Is it bad to have such huge constructors (my biggest one would take
28 parameters)?
Should you have a separate class for database
operations or is it better to have maybe an abstract class or
interface for it and let the subclasses themselves handle update, delete, insert?
Is it common to just write, delete from the database whenever or should I just apply these changes to my objects and only execute the commands to the database later, for example when the session ends?
I figure an application like this must have been done a fantastillion times before. What is the proper approach here? create objects, work with objects, save them to the database?
I have so many questions but I think many of them I just don't know how to ask.
Please note that if possible I would not like to use an ORM at this point.
Thank you very much for your time.
Questions posed in OP:
"Is it bad to have such huge constructors (my biggest one would take 28 parameters)"?
Yes. Imagine the calling code. You would have to pass 28 different values, not to mention each call would have to respect the exact order specified in the constructor. If one parameter was out of place, you could wreck havoc with parameter dependent algorithms. If you really need to pass a large number of parameters, I would recommend passing them in as an array (posted an example to another SO question).
"Should you have a separate class for database operations or is it better to have maybe an abstract class or interface for it and let the subclasses themselves handle update, delete, insert?"
Generally speaking, when creating classes, you want to try to identify the nouns that best represent your business needs. In your specific case you would probably have three classes; Company, Partner, and City.
Now within each class (noun), your methods would be in the form of verbs, so symantically your calling code makes sense: if ($company->getName() === 'forbes')
As you mentioned, each class needs a database object (dbo) to work with, so you could implement any number of patterns to expose datase connections to your classes; singleton, singleton with factory, or dependency injection, etc.
Abstract (parent) classes are great for sharing common algorithms across child classes, and should be identified when you are in the psuedo-code stage of your design. Parent classes also allow you to force child classes to have methods by declaring abstract methods within the parent.
Interfaces are a useful tool in certain situations, but I find they are less flexible than declaring abstract methods in parent class. But are good in situations where classes do not share a common parent.
"Is it common to just write, delete from the database whenever or should I just apply these changes to my objects and only execute the commands to the database later, for example when the session ends"?
CRUD activity should happen at the time the action is executed. If you wait for the session to end, you may run into situations where a session is pre-maturely ended due to a user closing a browser, for example. To better protect your data you can wrap your CRUD activity within transactions.
If you are running a high-traffic application, you can implement a queuing system and queue up the work to be done.
"I figure an application like this must have been done a fantastillion times before. What is the proper approach here? create objects, work with objects, save them to the database"?
You are correct, this has been done before, and are commonly referred to as ORMs (object relation mappers). Basically, an ORM will introspect your database schema, and create objects (and relations) which represent your schema. So instead of working with native SQL, you are working with objects. Although you can use SQL for custom business needs, but in the case of Doctrine, you would use Doctrine Query Language (DQL) vs native SQL.
An ORM I would highly recommend is Doctrine.
If you do not want to use an ORM, you can add CRUD methods to your primary classes. I Opted for an interface so your classes don't have to extend from a parent comprised of database operations. Also, check out this post on using a singleton/factory for exposing your classes database object(s).
Consider the following:
// Company.php
class Company implements iDatabaseOperation
public function delete()
{
// Lets use a DBO singleton/factory for DB access
// Uses PDO, which is strongly recommended
$dbo = Database::factory(Database::DATABASE_NAME);
$dbo->beginTransaction();
try {
$sql =
"DELETE FROM " .
" company " .
"WHERE " .
" id = :companyId " .
"LIMIT 1";
$stmt = $dbo->prepare($sql);
$stmt->bindValue(':companyId', $this->getId());
$stmt->execute();
$dbo->commit();
} catch (Exception $e) {
$dbo->rollback();
error_log($e->getMessage();
$e = null; // Php's garbage collection sucks
}
}
}
// iDatabaseOperation.php
interface iDatabaseOperation
{
public function delete();
public function update();
public function insert();
}
It is realy bad. Code is completele unreadable in this case. You have options
to use setters (can add validation logic inside, better readability, no need to fill empty fields with null)
to have separate class builder for each domain class (takes some memory for additional object). Example in java hope you can understand:
class CompanyBuilder {
private final Company c;
public CompanyBuilder() {
c = new Company();
}
CompanyBuilder addId(String id){c.id = id;}
// id should be package visible and class should be located in the same package with builder
CompanyBuilder addName(String name){...}
CompanyBuilder addCity(String city){...}
Company build(){ return c;}
}
hybrid solution to have methods to organise chain(worse debugging, better readability). In java will be methods:
class Company {
...
Company addId(String id){
this.id = id;
return this;
}
Company addName(String name){...}
...
}
Usage:
Company c = new Company().addId("1").addName("Name1");
maybe you can create more granular objects to reuse them later and add specific logic in correct place. For instance it can be Address(Location) object for company.
Follow single responsibility principle. SOLID description on wiki.
It helps to change database specific code without affection of other part of system in your case. Well, separate domain and database specific code, have common interface or abstract class(if you have common logic for all of domain classes - liskov principle). In subclasses implement domain specific part.
If you do not want to lose data you should save them each time or have cluster of servers or have distributed cache. If it is ok to lose save them in the end of session as batch. It will increase youre performance. Also you should save in transaction each time if you have concurrent updates.
Approach is get data from database/construct objects from this data or new objects/ work(update) objects/write data from objects to database
just write more code and read stackoverflow
Finally I suggest to read "Clean Code: A Handbook of Agile Software Craftsmanship" R.Martin.
You are essentially writing your own ORM. So, I wouldn't discount just switching to one that's already been written for you. The advantage to rolling your own is that you gain an understanding of how it works as your write it. But the disadvantage is that someone else has probably already done it better. But assuming you want to continue on...
General Advice: Remember to always break the problem down into simpler and simpler pieces. Each class should only perform a simple function. Also, you should not have to worry about caching updates... unless perhaps your database is on the other end of a remote connection over a modem.
Specific Advice follows:
I would setup your entity instance classes to house data and not to do a lot of data loading. Use other classes and logic for loading the data. I would use the constructor of the entity class only to populate the data that pertains to the class (and it's children).
A simple thing to do is to use static methods on the entity class for loading and saving data. E.g.
class city {
private $id = null;
private $name = null;
function __construct( $id, $name ) {
$this->id = $id;
$this->name = $name;
}
// getters and setters
...
// ---------------------
// static functions
// ---------------------
public static function loadById($cityId) {
// pull up the city by id
$retval = new city(row["id"], row["name"]);
// close db connection
return $retval;
}
public static function loadByCustomerId($customerId) {
// pull up multiple cities by customer id
// loop through each row and make a new city object
// return a hash or array of cities
}
public static function update($city) {
// generate your update statement with $city->values
}
// other methods for inserting and deleting cities
...
}
So now the code to get and update cities would look something like this:
// loading city data
$city = city::loadById(1); // returns a city instance
$cities = city::loadByCustomerId(1); // returns an array of city instances
// updating city data
$city->name = "Chicago"; // was "chicago"
city::update($city); // saves the change we made to $city
The static methods are not the best way to implement this, but it gets you pointed in the right direction. A repository pattern would be better, but that's beyond the scope of this one answer. I find that often I don't see the merit in a more involved solution like the repository pattern until I run into problems with the simpler solutions.
What you are doing looks greate. What you can add is an intermediate layer which maps your business object to your database(object relation mapping). There are a lot of object relational mapping api out there. Check this wikipedia list for ones you can use for PHP
I think a constructor with 28 parameters is too much, you should others classes managing some attributes having some stuff in common. You should give us what kind of others attributes you instanciated, and it could help you to find a way to make more common objects.
I think you should also create a class managing the operations and the database like a DBHandler with delete, update, and so on..
In my opinion, do modifications on tuples in your database directly after functions are called are important.
Why? Because it could avoid conflict, like the case you try to update an object which is supposed to be deleted for example, if you do modifications on your database at the end.
You might want to look at ruby on rails.
You don't necessarily have to switch over to it, but look at how they implement the MVC pattern and achieve CRUD.

How can I get Zend Db to return a rowset rather an array when performing a UNION query?

I have a result set that is the result of a MySQL UNION query. The code I am using to fetch the data is:
$union_select = $PagesTable->getAdapter()->select()
->union(array('(' . $legal_resources_select . ')', '(' . $pages_select . ')'));
$PagesTable->getAdapter()->fetchAll($union_select)
$PagesTable extends Zend_Db_Table_Abstract. The full select is too big to post here and I don't think it is relevant to this particular question. If I am wrong let me know.
Currently this is returning an array of results, but I want it to return a rowset object. I must also be able to specify the $_rowClass. This is necessary so I can add methods for formatting and manipulating the returned values.
Is this possible?
You cannot. The result set you are fetching is a composite, and not a set of Rows from the DB, so even if it were possible, its a pretty bad idea.
Zend_Db_Table is an implementation of the Table Data Gateway pattern more than Active Record.
What you describe would be possible usually under Active Record, and to do so, I'd suggest looking at Doctrine 1.2 rather than Zend_Db_Table.
BTW, if you want to specify the rowClass or rowsetClass, you can do that with the Zend_Db_Table class by calling the following methods
Using Zend_Db_Table's methods setRowsetClass and setRowClass:
class RowTable extends Zend_Db_Table_Abstract {
private static $_instance;
protected $_name = "tableName";
protected $_primary = "primary_key_id";
# over-write the default class Zend_Db_Table_Rowset_Abstract
# make sure the following classes are inside the include-path
private function __construct($rowClass, $rowsetClass) {
$this->setRowsetClass("ContributionList");
$this->setRowClass("Contribution");
}
}
$tableObject = new RowTable("RowClass", "RowsetClass");
By the way, I know this is really old, but the ones who get to this page should know that, a Zend_Db_Adapter always returns arrays, so when you use the Zend_Db_Table::getAdapter method, you are actually getting away from your table class and using the fetch method contained on the adapter class which returns array, rather than the Zend_Db_Table::_fetch which returns objects under the Data Gateway pattern.
So the first answer is wrong, the result set will be a row-set with many row objects but without what doctrine calls data hydration, so expect many redundant data on the row objects.
I see this mistake done by a lot of people where I work, I wonder why so many people uses the getAdapter method. Another thing to mention is that, when you use the getAdapter to get the select object, you are not getting the right select object, you are getting a Zend_Db_Select and you will need a Zend_Db_Table_Select so u can use on the Zend_Db_Table::_fetch method which is used by the fetchAll and fetchRow methods.
Cheers.

PHP PDO: Fetching data as objects - properties assigned BEFORE __construct is called. Is this correct?

The full question should be "Is this correct or is it some bug I can't count on?"
WHY is this correct behavior?
I've been working with PDO more and in particular playing with fetching data directly into objects. While doing so I discovered this:
If I fetch data directly into an object like this:
$STH = $DBH->prepare('SELECT first_name, address from people WHERE 1');
$obj = $STH->fetchAll(PDO::FETCH_CLASS, 'person');
and have an object like this:
class person {
public $first_name;
public $address;
function __construct() {
$this->first_name = $this->first_name . " is the name";
}
}
It shows me that the properties are being assigned before the __construct is being called -- because the names all have " is the name" appended.
Is this some bug (in which case I can't/won't count on it) or is this The Way It Should Be. Because it's really quite a nice thing the way it works currently.
Update
Apparently, according to one of the maintainers this is not a bug. Someone posted it as a bug in 2008, to which the reply was 'its not a bug, read the docs'.
However, I'd really like to know WHY this is correct behavior.
After much reading I think I finally came across the answer: it works this way intentionally, and you have the option of making it operate otherwise.
There's a mostly undocumented PDO constant called PDO::FETCH_PROPS_LATE which you can use to cause the properties to be fetched into the object after its been constructed. For example:
$obj = $STH->fetchAll(PDO::FETCH_CLASS | PDO::FETCH_PROPS_LATE, 'person');
Will cause the properties to be assigned AFTER the object is created, so my example above would not modify the properties at all. Leaving the PDO::FETCH_PROPS_LATE off, of course, causes it to act as described in my example in the original question.
The maintainers seem to have actively considered that both behaviors may be desirable and given you the option to do either. The documentation doesn't even explain it -- I was reading through a list of PDO constants and saw it, and gave it a shot.
The reason is, when you serialize an object, either to a database or a string, you don't (normally) want to reinitialise the properties when unserializing it.
Try using PDO::FETCH_INTO instead of PDO::FETCH_CLASS. From the docs:
PDO::FETCH_INTO: updates an existing instance of the requested class, mapping the columns of the result set to named properties in the class
So, you'd create the instance first, then pass the instance to your desired fetch method.
That being said, yeah it is rather counter-intuitive to have FETCH_CLASS populate before calling __construct. The answer given on the mailing list is the standard copy-and-paste "RTM" answer. If FETCH_INTO works, you should open a documentation bug with the suggested enhancement(s).

Parameters vs. Attributes(class variables)?

In OOP, is it better to use class attributes within class functions, or just pass parameters to them.
class User{
private $user = array();
public function Get_Existing_User($user_id){
//SQL selects user info for existing user
$this->user = mysqli_fetch_assoc();
}
public function Set_User($user_data){
$this->user = (array) $user_data;
}
public function Add_User(){
//insert everything from $this->user into database
}
public function Get_User(){
return $this->user;
}
}
VS
class User{
public function Get_Existing_User($user_id){
//SQL selects user info for existing user
$user = mysqli_fetch_assoc();
return $user;
}
public function Add_User($user_data){
//insert everything from $user_data into database
}
}
Whats the better way to go?
Between your solutions, first is better, but you have to change the names of the functions. 'get' should be used only if function returns something.
The reason it is better is that it doesn't use side effects, side effects always bad as they are invisible to user of the class but change class behavior. So you should try to minimize them or make them obvious as they are in the first case, when they not really 'side'.
But in this particular case, Get_Existing_User and Add_User should be static functions, that return new User object, it is sometimes called as static constructor. The reason why it is much better is that it makes it clear what that functions do, they get something as parameter (user_id of existing user or first_name, last_name and other attributes for a new user) and create an object that represents the user. All database manipulation will be hidden away. Object itself should have properties for name and other attributes and even Save() method to push the changes back. But main idea is that you always work with constructed object, object that already have context and linked to something in the real world (that is, user in the database), not an empty shell that will be filled in as you go.
Some clarification on terminology first:
What you call class functions are more properly called methods. A method is a function on an object instance. Additionally, classes may have methods. These are called class methods or static methods. When you use the term class function, you are thus confusing the meaning.
That settled, there is no worse or better of the two approaches. You would use both, depending on the context. Parameters have a smaller scope, and thus cause less coupling. If everything else is the same, I would therefore say that parameters are preferable to setting an object property.
That said, there are usually other factors that can determine which to pick. You can think of an object as a scope for related variables. If a variable belongs to that scope, it would make sense to assign it to a property.
Class attributes are expected to describe the state of an instance of the class known as an object. As such, the attributes can be used by any function of the class to modify it's state. Function parameters on the other hand may have nothing to do with the current state of the object but can be used to modify it's state.
For example: a user object could be expected to have a user name attribute, a password attribute, and an authenticated attribute. this user object also has a function called authenticate that takes a parameter which describes an authentication method. The parameter is used to modify the state of the user object but would not be held as an attribute of it.
That entirely depends on wether you're going to re-use the data and how you're using the Class.
If you create many individual instances of the Class and each Object represents a unique user, it makes sense to persist the data in a member variable. If you're using the Class as a DAO (data access object) with a lot of one-off operations, it probably doesn't make a lot of sense to persist the data. But even in a DAO, depending on its inner workings, it might make sense to store the data at least temporarily in a member variable if there are many functions involved in a single call (like beforeQuery and afterQuery callbacks or the like).
There's no one-better-way-fits-it-all.
It is important that you choose the method that best suits your situation. Ignoring that not-so-helpful suggestion I encourage you to take a good look at some important principles in Object Oriented Design
Coupling
Cohesion
A strong understanding of these topics will help you assess your situation and code to suit the goals of the project. As your project grows, you'll likely find that you'll want to use methods that have optional parameters to interact with your objects to achieve high cohesion and loose coupling. Then you'll use methods and parameters like an expert.

Should I be extending this class? (PHP)

I'm creating an ORM in PHP, and I've got a class 'ORM' which basically creates an object corresponding to a database table (I'm aiming for similar to/same functionality as an ActiveRecord pattern.) ORM itself extends 'Database', which sets up the database connection.
So, I can call: $c = new Customer();
$c->name = 'John Smith';
$c->save();
The ORM class provides this functionality (sets up the class properties, provides save(), find(), findAll() etc. methods), and Customer extends ORM. However, in the future I may be wanting to add extra public methods to Customer (or any other model I create), so should this be extending ORM or not?
I know I haven't provided much information here, but hopefully this is understandable on a vague explanation, as opposed to posting up 300+ lines of code.
I agree with the other answers here - put the additional methods into a descendant class. I'd also add an asterisk to that though: each time you extend the class with extra methods, think about what you are trying to achieve with the extension, and think about whether or not it can be generalised and worked back into the parent class. For example:
// Customer.class.php
function getByName($name) {
// SELECT * FROM `customer` WHERE `name` = $name
}
// ** this could instead be written as: **
// ORM.class.php
function getByField($field, $value) {
// SELECT * FROM `$this->table` WHERE `$field` = $value
}
You're certainly thinking correctly to put your business logic in a new class outside your 'ORM'. For me, instead simply extending the ORM-class, I'd rather encapsulate it with a new, value object class to provide an additional degree of freedom from your database design to free you up to think of the class as a pure business object.
Nope. You should use composition instead of inheritance. See the following example:
class Customer {
public $name;
public function save() {
$orm = new ORM('customers', 'id'); // table name and primary key
$orm->name = $this->name;
$orm->save();
}
}
And ORM class should not extend Database. Composition again is best suited in this use case.
Yes, place your business logic in a descendant class. This is a very common pattern seen in most Data Access Layers generation frameworks.
You should absolutely extend the ORM class. Different things should be objects of different classes. Customers are very different from Products, and to support both in a single ORM class would be unneeded bloat and completely defeat the purpose of OOP.
Another nice thing to do is to add hooks for before save, after save, etc. These give you more flexibility as your ORM extending classes become more diverse.
Given my limited knowledge of PHP I'm not sure if this is related, but if you're trying to create many business objects this might be an incredibly time consuming process. Perhaps you should consider frameworks such as CakePHP and others like it. This is nice if you're still in the process of creating your business logic.
You're definitely thinking along the right lines with inheritance here.
If you're building an ORM just for the sake of building one (or because you don't like the way others handle things) than go for it, otherwise you might look at a prebuilt ORM that can generate most of your code straight from your database schema. It'll save you boatloads of time. CoughPHP is currently my favorite.
I have solved it like this in my Pork.dbObject. Make sure to check it out and snag some of the braincrunching I already did :P
class Poll extends dbObject // dbObject is my ORM. Poll can extend it so it gets all properties.
{
function __construct($ID=false)
{
$this->__setupDatabase('polls', // db table
array('ID_Poll' => 'ID', // db field => object property
'strPollQuestion' => 'strpollquestion',
'datPublished' => 'datpublished',
'datCloseDate' => 'datclosedate',
'enmClosed' => 'enmclosed',
'enmGoedgekeurd' => 'enmgoedgekeurd'),
'ID_Poll', // primary db key
$ID); // primary key value
$this->addRelation('Pollitem'); //Connect PollItem to Poll 1;1
$this->addRelation('Pollvote', 'PollUser'); // connect pollVote via PollUser (many:many)
}
function Display()
{
// do your displayĆ­ng for poll here:
$pollItems = $this->Find("PollItem"); // find all poll items
$alreadyvoted = $this->Find("PollVote", array("IP"=>$_SERVER['REMOTE_ADDR'])); // find all votes for current ip
}
Note that this way, any database or ORM functionality is abstracted away from the Poll object. It doesn't need to know. Just the setupdatabase to hook up the fields / mappings. and the addRelation to hook up the relations to other dbObjects.
Also, even the dbObject class doesn't know much about SQL. Select / join queries are built by a special QueryBuilder object.

Categories