Php 在应用程序范围内共享实用程序功能
我在应用程序的许多类中使用了一些实用函数,例如:Php 在应用程序范围内共享实用程序功能,php,dependencies,Php,Dependencies,我在应用程序的许多类中使用了一些实用函数,例如: private function _trailingSlashIt($s) { return strlen($s) <= 0 ? '/' : ( substr($s, -1) !== '/' ? $s . '/' : $s ); } private function _endsWith($haystack, $needle) { return $needle === "" || substr($haystack, -strlen($nee
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; }
该解决方案的问题在于,它在我的类中创建了硬连线依赖项。(我宁愿复制每个类中的函数)。另一个想法是将实用程序类注入到我的对象中,但不知何故,这对于一些函数来说并不合适,我可能不得不将它们注入到我的许多对象中。
我想知道其他人会如何处理这个问题。谢谢你的建议 如果您有PHP5.4或更高版本,我会使用 但是,与使用静态类类似,但是您调用的是
$this->theUtility()
vsStringUtils::theUtility()
$path = StringUtils::trailingSlashIt($path);
<?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(...);
}
}
<?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;
}
}