I’ve secretly desired to implement the possibility to call all my library utility methods via one wrapper class alone to avoid having to remember method signatures like
\tad\utils\Arr::isAssoc($arr);
\tad\utils\Script::suffix($src);
Underscore
I’ve stumbled today on Underscore PHP library and fell in love with the idea to use the mixin
provided method to add methods to the class and be able to call them later like
__::isAssoc($arr);
__::suffix($src);
and I’ve put together a class extending __
to be able to do so
<?php
namespace tad\utils;
class __ extends \brianhaveri\__{
public static function __callStatic($name, $arguments)
{
self::maybeAddMethods();
return parent::__callStatic($name, $arguments);
}
public function __call($name, $arguments)
{
self::maybeAddMethods();
return $this->__call($name, $arguments);
}
private static $addedMethods = false;
private static function maybeAddMethods()
{
if (self::$addedMethods) {
return;
}
// for each other class defined in the utils folder
foreach (glob(dirname(__FILE__) . '/*.php') as $file) {
// if the file is '__.php' return
if ($file == __FILE__) {
continue;
}
$className = '\tad\utils\\' . basename($file, '.php');
// if the class has an 'addToUnderscore' method call it
if (method_exists($className, 'addToUnderscore')) {
$className::addToUnderscore();
}
}
self::$addedMethods = true;
}
}
Since the class is extending the original one all of __
original methods are available in the \tad\utils__
class and what the class is doing is to scan the folder containing the utility classes and call their defined addToUnderscore
method.
The \tad\utils\Str
class defines its like
<?php
namespace tad\utils;
class Str
{
public static function underscore($string)
{
...
}
public static function hyphen($string)
{
...
}
public static function camelCase($string)
{
...
}
public static function camelBack($string)
{
...
}
public static function ucfirstUnderscore($string)
{
...
}
public static function toPath($string)
{
....
}
public static function addToUnderscore()
{
if (class_exists('\brianhaveri\__')) {
\brianhaveri\__::mixin(
array(
'underscore' => function($string) { return \tad\utils\Str::underscore($string); },
'hyphen' => function($string) { return \tad\utils\Str::hyphen($string); },
'camelCase' => function($string) { return \tad\utils\Str::camelCase($string); },
'camelBack' => function($string) { return \tad\utils\Str::camelBack($string); },
'ucfirstUnderscore' => function($string) { return \tad\utils\Str::ucfirstUnderscore($string); },
'toPath' => function($string) { return \tad\utils\Str::toPath($string); }
)
);
}
}
}
While the process might seem convoluted it allows me to write my classes in an organized fashion and refer them later using just one use
statement like
// file SomeClass.php
namespace someNamespace;
use \tad\utils\__;
class SomeClass
{
...
}
in place of
// file SomeClass.php
namespace someNamespace;
use \tad\utils\Str;
use \tad\utils\Script;
use \tad\utils\Arr;
...
class SomeClass
{
...
}