There are some utility functions that I use in many classes of my application, some examples would be :
private function _trailingSlashIt($s) { return strlen($s) <= 0 ? '/' : ( substr($s, -1) !== '/' ? $s . '/' : $s ); }
private function _endsWith($haystack, $needle) { return $needle === "" || substr($haystack, -strlen($needle)) === $needle; }
private function _startsWith($haystack, $needle) { return $needle === "" || strpos($haystack, $needle) === 0; }
For the moment - until I find a better solution - I copy the functions I need in each class that uses them.
In a first attempt to avoid duplicate code, I had a utility (static) class, and I would do something like:
$path = StringUtils::trailingSlashIt($path);
The problem with that solution, is that it creates hard-wired dependencies in my classes. (I rather copy the functions in each class).
Another idea would be to inject the utility classes into my objects, but somehow this doesn't feel right, for just a few functions, and I might have to inject them in many of my objects.
I would like to know how others would deal with this problem. Thank you for any advice!
I would use traits if you have PHP 5.4 or later.
Kind of similar to using a static class, however, but you're calling $this->theUtility()
vs StringUtils::theUtility()
.
<?php
trait StringUtilTrait
{
private function trailingSlashIt($s)
{
return strlen($s) <= 0 ? '/' : ( substr($s, -1) !== '/' ? $s . '/' : $s );
}
// other stuff
}
class SomeClass
{
use StringUtilTrait;
public function someMethod()
{
// $this->trailingSlashIt(...);
}
}
Alternatively, you could use injection but provide the a default instance:
<?php
class StringUtil
{
// ...
}
class SomeClass
{
private $stringutil = null;
public function setStringUtil(StringUtil $util)
{
$this->stringutil = $util;
}
public function getStringUtil()
{
if (null === $this->stringutil) {
$this->stringutil = new StringUtil();
}
return $this->stringutil;
}
}