How to do a PHP nested class or nested methods?

How can I do this in PHP

$myDBClass->users()->limit(5);//output you limited users to 5 $myDBClass->comments()->limit(3);//output you limited comments to 3

what I meant is nested methods or nested class (I don't know!) so when I call the limit method as a child of users it will know that I am calling it from "users" method -or class- and when I call limit method -or class!- from comments It also knows that.

what is the possible structure for a PHP class to do this thing?



the reason for this question because I am working on my own class for database so I can easily use something like this

$DB->comments()->id(" > 3")->limit(10);

to generate the sql code "select * from comments where id > 3 limit 10" Thanks

--------------Solutions-------------

Have the methods return objects with the methods described, and you get what you are after.

So, as long as $DB is an object that has a comments()-method, that part is valid. If that comments() returns an object that has an id()-method, that part is valid, too. Then, id() needs to return an object that has the limit()-method.

In your particular case, you might want to do something like this:

class DB {
public function comments() {
// do preparations that make the object select the "comments"-table...
return $this;
}

public function id($string) {
// handle this too...
return $this;
}

public function limit($int) {
// also this
return $this;
}

public function execute() {
$success = try_to_execute_accumulated_db_commands();
return $success;
}
}

$DB = new DB();

In my example, every method (also not depicted here) would return the object itself, so that commands can be chained together. When the construction of the database query is done, you actually evaluate the query by invoking execute() that (in my case) would return a boolean that would represent the success of the database execution.

User nickohm suggested that this is called a fluent interface. I must admit that this is a new term for me, but that tells probably more of my knowledge, than the term's usage. ("I just write code, you know...")

Note: $this is a 'magic' variable that points to the currently active object. As the name suggests, it just returns itself as the return value for the method.

The standard convention for this is to return the instance of $this at the end of each of the method call. So when returned to the caller we are then just referencing another method call.

class Foo
{
public function do_something()
{
return $this;
}

public function do_something_else()
{
return $this;
}
}

$foo->do_something()->do_something_else();

A simple to implement method to get you started might go like:

class db
{
public function __call($function, $arguments)
{
switch($function) {
// implement table handling here
case 'user':
//do something
return $something;
break;
}
}
}

Depending on whether or not you want to go complicated, but solid or simple, but less flexible you might implement two different strategies. Simple strategy might go like so:

class db
{

protected $operatingTable;

public function limit($limitNumber)
{
return $this->executeQuery("SELECT * FROM ".$this->operatingTable." LIMIT ".$limitNumber); // where executeQuery is a function that runs a query
}

public function __call($function, $arguments)
{
switch($function) {
// implement table handling here
case 'user':
$this->operatingTable='user'; // alternately, but less secure: $this->operatingTable=$function;
return $this;
break;
}
}
}

Alternately, but more powerful:

class db
{
protected $operatingTable;

public function limit($limitNumber)
{
return $this->executeQuery("SELECT * FROM ".$this->operatingTable." LIMIT ".$limitNumber); // where executeQuery is a function that runs a query
}

public function __call($function, $arguments)
{
switch($function) {
// implement table handling here
case 'user':
$user = new user($this); // pass in the database to the object, so the table object can have a reference to the db
return $user;
break;
}
}
}

class baseTableClass
{
protected $db; // an instance of class db

function limit($limitNumber)
{
$db->execute($aStatementDerivedFromThisClassesInformation); // execute a sql command, based on information about the table in the class
}

}

class user extends baseTableClass
{
public function __construct($db) {
$this->db = $db;
}
}

You get the idea. Either overload the db object, or create a base db object, and table objects, putting much of the intelligence in table objects, ensuring that when created, a table object stores a reference to the db object

Category:php Time:2009-02-10 Views:0

Related post

  • Nested content_tag throws undefined method `output_buffer=` in simple helper 2011-01-08

    I'm trying to create a simple view helper but as soon as I try nest a couple of content tags it will throw NoMethodError: undefined method `output_buffer=' for def table_for(list, &proc) t = Table.new proc.call(t) t.render_column(list) end class

  • How can a nested class access a method in the outer class in Ruby? 2011-02-04

    def class A def a raise "hi" #can't be reached end class B def b a() #doesn't find method a. end end end I want to invoke a from b and raise the exception. How can I? --------------Solutions------------- Ruby doesn't have nested classes. The only way

  • Nested IF or nested CASE SELECT 2012-10-21

    Hi, No particular problem to solve just a general question. Is there any advantage in using nested IF or nested CASE SELECT statements to test for a series of conditions? I realise that there is a limit to the number of nested IFs that are permissabl

  • HTML/CSS: what's a better option for layout of a tree of nested elements than nested tables? 2009-01-27

    Ok, I have a set of checkboxes for selecting criteria. For argument's sake, we'll say the data looks like this: [] Vehicles [] Unpowered [] Bicycle [] Skateboard [] Powered [] Two-wheeled [] Motorcycle [] Scooter [] Four-wheeled etc The []s represent

  • nested dictionary to nested repeater asp.net c# 2009-05-29

    I'm making an asp.page that will display hierarchical information about company assets. To grab the data I used a lambda expression: FASAssetInfoDataContext fasInfo = new FASAssetInfoDataContext(); var data = from g in fasInfo.Asset_Informations wher

  • How can I handle nested looping without nesting foreach statements in Perl? 2009-08-26

    I have a Perl script which nests foreach loops as seen below. It takes a long time: #! /usr/bin/perl use strict; use warnings; my @sites = ('a', 'b', 'c'); my @servers = ('A', 'B'); my @data_type = ("X", "Y", "Z"); foreach my $site (@sites) { foreach

  • Nested or not nested if-blocks? 2009-11-01

    I was wondering if there is a performance difference when using ifs in C#, and they are nested or not. Here's an example: if(hello == true) { if(index == 34) { DoSomething(); } } Is this faster or slower than this: if(hello == true && index =

  • Recursive php function that turns nested array into nested html blocks 2009-11-19

    I'm looking to write a recursive php function that would call a function to generate nested HTML blocks ( not necessarily only DIVs ). So for example, for the following array: $a = array( 'b' => 'b value', 'c' => 'c value', 'd' => array( 'd1

  • Nested Layout for Nested Resources in Rails 2009-12-09

    Is it possible to automatically assign a specified layout template to a particular controller and all of the resources nested within it, as specified in routes.rb? This layout should apply only the specified controller views and those nested within i

  • Best Practice for Transitioning From Nested State to Nested State (see diagram) 2010-01-18

    I am trying to wrap my mind around the best way to implement nested state transitions in a single threaded programming language (Actionscript). Say I have a structure like this behavior tree: Now imagine that each leaf node is a destination point on

  • How to avoid using duplicate savepoint names in nested transactions in nested stored procs? 2010-04-09

    I have a pattern that I almost always follow, where if I need to wrap up an operation in a transaction, I do this: BEGIN TRANSACTION SAVE TRANSACTION TX -- Stuff IF @error <> 0 ROLLBACK TRANSACTION TX COMMIT TRANSACTION That's served me well en

  • Rails nested form with nested resource: update belongs_to association when creating new has_many 2010-06-18

    Hey guys, I've been beating my head against a wall with a particular use case for nested forms (I'm using Rails 2.3.5). Essentially I have Project and Payment models that looks like this class Project < ActiveRecord::Base has_many :payments end cl

  • WPF: Converting nested DrawingGroup to nested DrawingVisual 2010-08-17

    I have a DrawingGroup with nested children created from SVG files and I want to render/convert this to a corresponding nested DrawingVisual/Visual. A simple rendering process, as follows... DrawingGroup group; // assuming root group of diagrams Drawi

  • Nested models throws Undefined Method Error 2010-08-29

    I've been following RailsCast 197 to try this nested models/forms and have cracked my head over this code for over 2 hours, but to no avail. What am I overlooking? I have the following Models: class Workout < ActiveRecord::Base belongs_to :user ha

  • Reusing form nested and not nested, how to show submit button 2010-09-28

    I'm learning rails and building a recipe app. In my app, a Recipe has a bunch of ingredients. I've got my ingredients form nested within my recipe form, and I call it with a partial. Of course, because the form is nested, the <%= f.submit %> is

  • Merge nested dictionaries, by nested keys? 2010-11-20

    I have several dictionaries with different and common keys, plus different and common keys in the nested dictionary. Below is a simplified example, the actual dictionaries have thousands of keys. {1:{"Title":"Chrome","Author":"Google","URL":"http://"

  • How do I group by a Nested property's Nested property (part II) 2010-11-21

    In a previous post (http://bit.ly/bbIthV) i asked how to Group a list of Persons by their nested Address.State, when Address might be null. Jon Skeet gave a perfect answer to my question: //Create a dummy replacement for when a person has no addresse

  • Why can't I return only in a nested body of my Method and not be forced to return in the scope of the main method? 2010-12-20

    Why is it that if you declare a return type on a method, that you have to specify a return in the scope of that method? Meaning, if I have a If/Switch in my method I can't specify the return there "ALONE" and not in the main method body? Is the only

  • Produce Nested XML using muenchian method in XLST 2011-06-20

    I am trying to produce a nested XML document from a flat XML document as below. After searching here and other resources available on the net it seems that that the muenchain method could be the solution however I am struggling applying it to my situ

Copyright (C) pcaskme.com, All Rights Reserved.

processed in 0.554 (s). 13 q(s)