ホームページ  >  記事  >  バックエンド開発  >  php_PHP チュートリアルでリフレクションを使用してプラグイン メカニズムを実装する方法

php_PHP チュートリアルでリフレクションを使用してプラグイン メカニズムを実装する方法

WBOY
WBOYオリジナル
2016-07-13 10:03:17921ブラウズ

PHP がリフレクションを使用してプラグイン メカニズムを実装する方法

この記事では、PHP がリフレクションを使用してプラグイン メカニズムを実装する方法の例について説明します。参考のためにみんなで共有してください。具体的な実装方法は以下の通りです

コードは次のとおりです:

/**
* @name PHP Reflection API -- リフレクション技術を使用して実装されたプラグイン システム アーキテクチャ
​*/
インターフェイスプラグイン{
    パブリック静的関数 getName();   
}
関数 findPlugins(){
    $plugins = array();   
    foreach (get_declared_classes() as $class){
        $reflectionClass = 新しい ReflectionClass($class);   
        if ($reflectionClass->implementsInterface('Iplugin')) {
            $plugins[] = $reflectionClass;   
        }
    }
    $plugins を返します。   
}
関数 computeMenu(){
    $menu = 配列();   
    foreach (findPlugins() として $plugin){
        if ($plugin->hasMethod('getMenuItems')) {
            $reflectionMethod = $plugin->getMethod('getMenuItems');   
            if ($reflectionMethod->isStatic()) {
                $items = $reflectionMethod->invoke(null);   
            } その他 {
                $pluginInstance = $plugin->newInstance();   
                $items = $reflectionMethod->invoke($pluginInstance);   
            }
            $menu = array_merge($menu,$items);   
        }
    }
    $menuを返す;   
}
関数 computeArticles(){
    $articles = 配列();   
    foreach (findPlugins() として $plugin){
        if ($plugin->hasMethod('getArticles')) {
            $reflectionMethod = $plugin->getMethod('getArticles');   
            if ($reflectionMethod->isStatic()) {
                $items = $reflectionMethod->invoke(null);   
            } その他 {
                $pluginInstance = $plugin->newInstance();   
                $items = $reflectionMethod->invoke($pluginInstance);   
            }
            $articles = array_merge($articles,$items);   
        }
    }
    $articles を返します。   
}
クラス MycoolPugin は Iplugin {
を実装します     パブリック静的関数 getName(){
        'MycoolPlugin' を返します。   
    }
    パブリック静的関数 getMenuItems(){
        return array(array('description'=>'MycoolPlugin','link'=>'/MyCoolPlugin'));   
    }
    パブリック静的関数 getArticles(){
return array(array('path'=>'/MycoolPlugin','title'=>'これは本当に素晴らしい記事です','text'=> 'xxxxxxxxx' )); }
}
$menu = computeMenu(); $articles = computeArticles(); プリント_r($メニュー); print_r($articles);



この記事で説明した内容が皆様の PHP プログラミング設計に役立つことを願っています。

http://www.bkjia.com/PHPjc/969331.html

www.bkjia.com

http://www.bkjia.com/PHPjc/969331.html技術記事 PHP がリフレクションを使用してプラグイン メカニズムを実装する方法 この記事では、PHP がリフレクションを使用してプラグイン メカニズムを実装する方法について説明します。参考のためにみんなで共有してください。具体的な実装方法は以下の通りです。 コードは以下の通りです...
声明:
この記事の内容はネチズンが自主的に寄稿したものであり、著作権は原著者に帰属します。このサイトは、それに相当する法的責任を負いません。盗作または侵害の疑いのあるコンテンツを見つけた場合は、admin@php.cn までご連絡ください。