繁体   English   中英

PHP强制函数调用

[英]PHP mandatory function call

我知道可以使用接口来强制执行函数的定义,但是我找不到能使用户强制执行函数调用的东西,例如,如果我创建一个类而成为另一个类的成员(通过扩展等),则使用一个函数,以便该类自动确保强制性函数随该函数一起部分调用。

我的意思是,进一步澄清:

class domain {

   function isEmpty($input) {
      //apply conditional logic and results
   }
}
class test extends domain {

   function addTestToDBTable($test) {
      /** 
       *  try to add but this class automatically makes it so that all rules of
       *  class domain must be passed before it can run
       *  - so essentially, I am no longer required to call those tests for each and
       *    every method 
       **/  
   }
 }

抱歉,无论如何,这似乎是不连贯的。 当然,这似乎很懒,但是我希望能够强制上下文而不必担心

更新:

好的,进一步澄清一下:在PHP中,如果我为子类扩展并声明__construct(),则该子类将覆盖父__construct()。 我不希望这样,我希望保留父构造并根据孩子的意愿随意执行任务,就像子类也可以这样做一样。

我想可以用两种不同的方式来完成。

面向方面的编程

在这里看看https://github.com/AOP-PHP/AOP

生成或编写代理类

一个非常简单的示例可能是:

<?php
class A {
    public function callMe() {
        echo __METHOD__ . "\n";
    }
}

class B extends A {

    // prevents instantiation
    public function __construct() {
    }

    public function shouldCallMe() {
        echo __METHOD__ . "\n";
    }

    public static function newInstance() {
        return new ABProxy();
    }
}

class ABProxy {
    private $b;

    public function __construct() {
        $this->b = new B();
    }

    public function __call($method, $args) {
        $this->b->callMe();
        return call_user_func_array(array($this->b, $method), $args);
    }
}

// make the call
$b = B::newInstance();
$b->shouldCallMe();

// Outputs
// ------------------
// A::callMe
// B::shouldCallMe

希望这会有所帮助。

听起来好像您想要装饰器

有关如何执行此操作的详细说明,请参见此答案 请注意,它不需要类扩展。

我将使用带有某些文档块元编程魔术的域验证装饰器。 但这确实是整个图书馆的工作,这无疑是存在的。

小提琴

<?php
class FooDomain {
    public static function is_not_empty($input) {
        return !empty($input);
    }
}

class Foo {
    /**
     * @domain FooDomain::is_not_empty my_string
     */
    public function print_string($my_string) {
        echo $my_string . PHP_EOL;
    }
}

$foo = new DomainValidator(new Foo());
$foo->print_string('Hello, world!');
try {
    $foo->print_string(''); // throws a DomainException
} catch (\DomainException $e) {
    echo 'Could not print an empty string...' . PHP_EOL;
}

// ---

class DomainValidator {
    const DOMAIN_TAG = '@domain';

    private $object;

    public function __construct($object) {
        $this->object = $object;
    }

    public function __call($function, $arguments) {
        if (!$this->verify_domain($function, $arguments)) {
            throw new \DomainException('Bad domain!');
        }

        return call_user_func_array(
            array($this->object, $function),
            $arguments
        );
    }

    public function __get($name) {
        return $this->object->name;
    }

    public function __set($name, $value) {
        $this->object->name = $value;
    }

    private function verify_domain($function, $arguments) {
        // Get reference to method
        $method = new \ReflectionMethod($this->object, $function);
        $domains = $this->get_domains($method->getDocComment());
        $arguments = $this->parse_arguments(
            $method->getParameters(),
            $arguments
        );
        foreach ($domains as $domain) {
            if (!call_user_func(
                $domain['name'],
                $arguments[$domain['parameter']]
            )) {
                return false;
            }
        }
        return true;
    }

    private function get_domains($doc_block) {
        $lines = explode("\n", $doc_block);
        $domains = array();
        $domain_tag = DomainValidator::DOMAIN_TAG . ' ';
        foreach ($lines as $line) {
            $has_domain = stristr($line, $domain_tag) !== false;
            if ($has_domain) {
                $domain_info = explode($domain_tag, $line);
                $domain_info = explode(' ', $domain_info[1]);
                $domains[] = array(
                    'name'      => $domain_info[0],
                    'parameter' => $domain_info[1],
                );
            }
        }
        return $domains;
    }

    private function parse_arguments($parameters, $values) {
        $ret = array();
        for ($i = 0, $size = sizeof($values); $i < $size; $i++) {
            $ret[$parameters[$i]->name] = $values[$i];
        }
        return $ret;
    }
}

输出:

Hello, world!
Could not print an empty string...

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM