【问题标题】:Sharing utility functions application-wide在应用程序范围内共享实用程序功能
【发布时间】:2013-11-25 11:02:50
【问题描述】:

我在应用程序的许多类中都使用了一些实用函数,例如:

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; }

目前 - 在我找到更好的解决方案之前 - 我在每个使用它们的类中复制我需要的函数。

在第一次尝试避免重复代码时,我有一个实用程序(静态)类,我会这样做:

$path = StringUtils::trailingSlashIt($path);

该解决方案的问题在于它在我的类中创建了硬连线依赖项。 (我宁愿复制每个类中的函数)。

另一个想法是将实用程序类注入到我的对象中,但不知何故,这对于一些函数来说感觉不对,我可能不得不将它们注入到我的许多对象中。

我想知道其他人将如何处理这个问题。谢谢你的建议!

【问题讨论】:

    标签: php dependencies


    【解决方案1】:

    如果您有 PHP 5.4 或更高版本,我会使用 traits

    有点类似于使用静态类,但是您调用的是 $this-&gt;theUtility()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(...);
        }
    }
    

    或者,您可以使用注入但提供默认实例:

    <?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;
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-02-29
      • 2017-02-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-05-20
      • 1970-01-01
      相关资源
      最近更新 更多