myheritage/php-friendly

为PHP应用程序添加非本地类友元功能的实用程序

v1.1.0 2020-03-31 08:19 UTC

This package is not auto-updated.

Last update: 2024-09-25 05:30:58 UTC


README

为PHP应用程序添加非本地类友元功能的实用程序

概述

类友元 RFC 建议类友元将是PHP的本地特性。由于被拒绝,我们决定开发自己的非本地解决方案,以解决相同的问题——如何在同一命名空间下的多个类之间建立“友元”关系,并允许它们相互调用受保护的方法。

要求

  • PHP >= 7.3
  • php-unit >= 8.3

Composer安装

如果您使用Composer管理项目依赖,请将myheritage/php-friendly依赖项添加到您的项目中。

$ composer require myheritage/php-friendly

使用示例

被调用者

共享/公开的函数必须使用@friendly注解

<?php
namespace MyHeritage\Friends\Tests\Friendly;

use MyHeritage\Friends\Friendly;

class AFriendlyClass
{
    use Friendly;

    /**
     * @friendly
     * @param $message
     * @return mixed
     */
    protected function friendlyMethod($message)
    {
        return $message;
    }

    protected function notFriendly()
    {
        return "Booo";
    }
}

调用者

<?php
namespace MyHeritage\Friends\Tests\Friendly;

class MyClass
{
    public function getHelpFromAFriendlyClass()
    {
        echo (new AFriendlyClass())->friendlyMethod('hello, can you give a hand?');
    }
}