Thursday, September 30, 2010

mock table data

I got tired for looking at multidimensional arrays when writing lots of mock table data.


$orders = array(
array('email' => 'shaunxcode@gmail.com', 'firstname' => 'shaun', 'lastname' => 'gilchrist', 'street' => '555 north 800 east', 'city' => 'Orem', 'state' => 'UT', 'zip' => '84097', 'country' => 'USA', 'phone' => '801-222-5555'),
array('email' => 'peter@gmail.com', 'firstname' => 'peter', 'lastname' => 'jensen', 'street' => '5555 windsor street', 'city' => 'Salt Lake City', 'state' => 'UT', 'zip' => '84105', 'country' => 'USA', 'phone' => '801-555-0445'));

$orders = Voltron_Test::MockTable("
email | firstname | lastname | street | city | state | zip | country | phone
shaunxcode@gmail.com | shaun | gilchrist | 555 north 800 east | Orem | UT | 84097 | USA | 801-222-5555
peter@gmail.com | peter | jensen | 5555 windsor street | Salt Lake City | UT | 84105 | USA | 801-555-0445
");

#relevant Volron_Test::MockTable method

public static function MockTable($data)
{
$rows = array();
foreach(explode("\n", $data) as $row) {
if(empty($row)) {
continue;
}
$row = array_map('trim', explode('|', $row));
if(!isset($cols)) {
$cols = $row;
continue;
}
$rows[] = array_combine($cols, $row);
}
return $rows;
}

Thursday, September 23, 2010

instantiating object inline via __callStatic

This is a nice hack for instantiating objects inline via php 5.3 __callStatic. What I dig about it v.s. the newObject('ClassName') is that a) You can pass in arbitrary constructors, w/ newObject it only supported the case of there being a single param to constructor i.e. newObject('ClassName', $x)->otherFunc($y) can now be N::ClassName($x)->otherFunc($y). I think I like the fact the class can be a "bare word" and that any number of constructors can be passed thus legacy classes etc. which may require arbitrary arguments can also be used.


class Test {
public function __construct($name, $age)
{
echo "Name: $name and Age: $age passed to constructor\n";
}
}

class N {
public static function __callStatic($className, $args)
{
$class = new ReflectionClass($className);
return $class->newInstanceArgs($args);
}
}

N::Test('some name', 300);