programing

WordPress 플러그인:어떻게 하면 '긴밀 커플링'을 피할 수 있을까요?

elseif 2023. 4. 4. 21:06

WordPress 플러그인:어떻게 하면 '긴밀 커플링'을 피할 수 있을까요?

WordPress Plugin을 사용하고 있으며 베스트 프랙티스를 확보하려고 합니다.2개의 클래스가 있습니다.필요한 플러그인 클래스 "Jargonaut"와 다음 클래스에 포함된 "Dictionary"입니다.require_once()내 메인 플러그인 파일로 변환합니다.

Jonesaut 클래스의 대부분의 코드는 초기화를 다루고 컨트롤러와 같은 기능을 제공하지만, 대부분의 코드는 사전 개체를 사용하는 것에 크게 의존하고 있습니다(즉, 용어에 대한 저의 이해와 밀접하게 관련되어 있습니다).사전 클래스는 (MVC 아키텍처에서) 모델에 가깝고 데이터베이스와 인터페이스하기 때문에 구분하고 싶습니다.

타이트 커플링과 루즈 커플링의 회색 부분이 많이 보이는데 어느 정도인지 판단하기가 어렵습니까?

플러그인에 사전 개체가 필요한 경우 플러그인은 다음과 같이 요청해야 합니다.

class MyPlugin
{
    /**
     * @var Dictionary
     */
    private $dictionary;
    private function __construct(Dictionary $dictionary)
    {
        $this->dictionary = $dictionary;
    }

이것으로, 플러그 인이 느슨하게 연결되었습니다.Dictionary플러그인 클래스는 사전이 삽입되어 있기 때문에 더 이상 사전을 직접 만들 책임이 없습니다.필요한 걸 가져가야 해

그럼 그게 어떻게 작동할까요?플러그인은 어딘가에서 작성해야 하므로 팩토리가 필요합니다.공장 구축 방법에서는 플러그인에 필요한 것을 알고 있습니다.

class MyPluginFactory
{
    public static function build($pluginName)
    {
        $plugin = NULL;
        switch($pluginName)
        {
            case 'MyPlugin':
                $dictionary = new Dictionary();
                $plugin = new MyPlugin($dictionary);
        }
        return $plugin;
    }
}

이것은 워드프레스이기 때문에 플러그인의 부트스트래핑은 플러그인 파일을 포함시킴으로써 이루어진다는 것을 알고 있습니다.따라서 처음에 플러그인을 생성해야 합니다.글로벌 스코프에 포함되어 있듯이 플러그인 오브젝트는 메모리에 보존하고 싶지만 글로벌 변수로 사용할 수 없습니다.이로 인해 여러 플러그인 인스턴스를 생성할 수 있지만 워드프레스가 플러그인을 초기화할 때(플러그인을 로드) 해당 단일 인스턴스만 사용할 수 있습니다.이는 플러그인 팩토리를 추가 기능으로 함으로써 수행할 수 있습니다.

class MyPluginFactory
{
    ...
    public static $plugins;
    public static function bootstrap($pluginName)
    {
        $plugin  = self::build($pluginName);
        self::$plugins[] = $plugin;
        return $plugin;
    }

정적 클래스 멤버 변수는 플러그인이 메모리에 남아 있는지 확인하는 데에만 사용되므로 주의하십시오.이것은 기술적으로 우리가 방지하고 싶은 글로벌 변수이지만, 인스턴스는 어딘가에 저장해야 하기 때문에 여기에 있습니다(이는 글로벌 변수이기 때문에 부끄러워해서는 안 되기 때문에 public으로 변경했습니다).공공을 보유하는 것은 개인 또는 보호가 너무 제한적인 상황에서 도움이 될 수 있습니다.또한 그것은 문제가 되지 않을 것이다.문제가 있으면 먼저 해결해야 할 다른 문제가 있습니다.)

기본적으로 플러그인 코드를 워드프레스 자체에서 분리합니다.또한 사용하고 있는 워드프레스 함수에 직접 구속되지 않고 플러그인 코드가 워드프레스 자체와 느슨하게 결합되도록 하기 위해 클래스를 만들고 싶을 수도 있습니다.

class WordpressSystem
{
    public function registerFilter($name, $plugin, $methodName)
    {
        ... do what this needs with WP, e.g. call the global wordpress function to register a filter.
    }
    ...
}

다음 이 필요한 합니다.WordpressSystem작업을 수행하는 방법(일반적으로 해당):

class MyPlugin
{
    ...
    public function __construct(WordpressSystem $wp, Dictionary $dictionary)
    ...

마지막으로 이 문제를 정리하려면 플러그인 php 파일만 필요합니다.

<?php
/*
 * MyPlugin
 * 
 * Copyright 2010 by hakre <hakre.wordpress.com>, some rights reserved.
 *
 * Wordpress Plugin Header:
 * 
 *   Plugin Name:    My Plugin
 *   Plugin URI:     http://hakre.wordpress.com/plugins/my-plugin/
 *   Description:    Yet another wordpress plugin, but this time mine
 *   Version:        1.2-beta-2
 *   Stable tag:     1.1
 *   Min WP Version: 2.9
 *   Author:         hakre
 *   Author URI:     http://hakre.wordpress.com/
 *   Donate link:    http://www.prisonradio.org/donate.htm
 *   Tags:           my
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
 */
Namespace MyPlugin;

# if your file is named 'MyPlugin.php' this will be 'MyPlugin'.
return PluginFactory::bootstrap(basename($plugin, '.php'));

class PluginFactory
{
    private static $plugins;
    public static function bootstrap($pluginName)
    {
        $plugin = self::build($pluginName);
        self::$plugins[] = $plugin;
        return $plugin;
    }
    public static function build($pluginName)
    {
        $plugin = NULL;
        switch($pluginName)
        {
            case 'MyPlugin':
                # Make your plugin work with different Wordpress Implementations.
                $system = new System\Wordpress3();
                $dictionary = new Dictionary();
                $plugin = new Plugin($system, $dictionary);
        }
        return $plugin;
    }
}

class Plugin
{
    /**
     * @var System
     */
    private $system;
    /**
     * @var Dictionary
     */
    private $dictionary;
    private function __construct(System $system, Dictionary $dictionary)
    {
        $this->system = $system;
        $this->dictionary = $dictionary;
    }

...

부트스트랩 방식에서는 오토로더 등록이나 요구 사항을 처리할 수도 있습니다.

이게 도움이 됐으면 좋겠네요.

언급URL : https://stackoverflow.com/questions/8688738/wordpress-plugin-how-do-i-avoid-tight-coupling