TalkPHP

TalkPHP (http://www.talkphp.com/forums.php)
-   General (http://www.talkphp.com/general/)
-   -   class? (http://www.talkphp.com/general/5617-class.html)

jwilson122 11-02-2010 12:08 AM

class?
 
Hey, I was wondering if anyone could give me an example script or show me how to make a class like such:
PHP Code:

$do->Query("SELECT * FROM users")->Where("id = 1")->extra("LIMIT 1"); 

See, I know how to make a class and functions inside of the class to make:
PHP Code:

$do->Query("SELECT * FROM users");
$do->Where(""id 1");
$do->extra("LIMIT 1"); 

But I would rather have the single line link..
PHP Code:

$do->Query("SELECT * FROM users")->Where("id = 1")->extra("LIMIT 1"); 

Is this considered OOP (object oriented programming) ? I've searched and searched for this, tried many things.. nothings working :/ any help? Thanks!

tony 11-02-2010 01:22 AM

that is call method chaining. If the methods Query, Where, and extra (and whichever other method that needs chaining) you just need to return the current instance of the class that $do is an instance of. for example, at the end of the Query method just put, return $this;

there is a tutorial/article here

jwilson122 11-02-2010 02:18 AM

Would you guys recommend just doing like..
PHP Code:

$_db->query("SELECT * FROM bla bla"); 

?? Or making a class chain?

jgetner 11-02-2010 05:21 AM

ether or is fine really depends on your needs for the application you are constructing.

here is a great article about here on TP

http://www.talkphp.com/advanced-php-...-chaining.html

Gibou 11-02-2010 09:45 AM

I would have done the same as Tony.
A class with methods "Query", "Where", "Limit", etc... + a property "Results" pointing on a private collection storing the results of the query.
The method "Query" puts the results of the query in the private collection and then, the methods "Where" and "Limit" make the limitations in the collection.

The bad thing in that is that it can returns a lot of unnecessary data but for the case you don't want to apply a "where" clause after the "Query", it's ok.

Village Idiot 11-02-2010 03:28 PM

Even if you can get this working it is a bad idea, SQL is SQL and PHP is PHP; dont mix them. There is no valid reason to be defining parts of your query like that, it can create bugs and severely limits your ability to write clean queries queries if they are to get complex. The default MySQL library for PHP is bad enough as is, dont make it worse.


All times are GMT. The time now is 04:39 PM.

Powered by vBulletin® Version 3.6.8
Copyright ©2000 - 2013, Jelsoft Enterprises Ltd.
Search Engine Optimization by vBSEO 3.1.0