Как добавить автозаполнение в классы, созданные с помощью пользовательской функции? - PullRequest
0 голосов
/ 24 сентября 2019

Я создаю свои классы с помощью пользовательских функций.

Классы находятся в app / code / core / например

app / code / core / Property/Helper/Property.php

require_once("Core/Helper.php");

class Property_Helper_Property extends Core\Helper
{
    public function __construct($con)
    {
        parent::__construct($con);
    }

    public function test()
    {
        return "hello";
    }

}

app / code / core / Core / Helper.php

<?php
namespace Core;

abstract class Helper
{
    protected $con;

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

Я могу позвонитьметод test() класса Property_Helper_Property из любого файла, подобного следующему:

require_once 'app/Main.php';  // always needed

Main::getHelper("Property/Property")->test();

app / Main.php

Этот файл содержит последний класс "Main ", который имеет статический метод getHelper

if (!defined('DS')) define('DS', DIRECTORY_SEPARATOR);
if (!defined('PS')) define('PS', PATH_SEPARATOR);
if (!defined('BP')) define('BP', dirname(dirname(__FILE__)));

/**
 * Set include path
 */
    Main::register('original_include_path', get_include_path());

    $paths = array();
    $paths[] = Main::CORE_PATH;
    $paths[] = Main::LOCAL_PATH;
    $paths[] = BP . DS . 'lib';
    $paths[] = BP . DS . 'inc';

    $appPath = implode(PS, $paths);
    set_include_path($appPath . PS . Main::registry('original_include_path'));

final class Main
{
    const CORE_PATH = BP . DS . 'app' . DS . 'code' . DS . 'core';
    const LOCAL_PATH = BP . DS . 'app' . DS . 'code' . DS . 'local';

    /**
     * Registry collection
     *
     * @var array
     */
    static private $_registry = array();

    public static function getDbConnection()
    {
        return self::registry("db_connection");
    }

    /**
     * Register a new variable
     *
     * @param string $key
     * @param mixed $value
     * @param bool $graceful
     */
    public static function register($key, $value, $graceful = false)
    {
        if (isset(self::$_registry[$key])) {
            if ($graceful) {
                return;
            }
            self::throwException('Main registry key "'.$key.'" already exists');
        }
        self::$_registry[$key] = $value;
    }

    /**
     * Unregister a variable from register by key
     *
     * @param string $key
     */
    public static function unregister($key)
    {
        if (isset(self::$_registry[$key])) {
            if (is_object(self::$_registry[$key]) && (method_exists(self::$_registry[$key], '__destruct'))) {
                self::$_registry[$key]->__destruct();
            }
            unset(self::$_registry[$key]);
        }
    }

    /**
     * Retrieve a value from registry by a key
     *
     * @param string $key
     * @return mixed
     */
    public static function registry($key)
    {
        if (isset(self::$_registry[$key])) {
            return self::$_registry[$key];
        }
        return null;
    }

    public static function getHelper($name)
    {
        $classPath = self::getClassPath($name, "Helper");
        if (!$classPath) { return false; }

        $fullClassPath = self::getFullClassPath($classPath);
        if (!$fullClassPath) { return false; }

        $obj = self::getClassInstance($fullClassPath, $classPath);
        if (!$obj) { return false; }

        return $obj;
    }

    public static function getModel($name)
    {
        $classPath = self::getClassPath($name, "Model");
        if (!$classPath) { return false; }

        $fullClassPath = self::getFullClassPath($classPath);
        if (!$fullClassPath) { return false; }

        $obj = self::getClassInstance($fullClassPath, $classPath);
        if (!$obj) { return false; }

        return $obj;
    }

    private function getClassInstance($fullClassPath, $classPath)
    {
        if (!$classPath) { return false; }

        require_once($fullClassPath);

        $className = str_replace("/", "_", $classPath);

        if (class_exists($className)) {
            return new $className(self::getDbConnection());
        } else {
            return false;
        }
    }

    private function getFullClassPath($classPath)
    {
        $modulPaths = [self::CORE_PATH, self::LOCAL_PATH];
        return self::checkIfFileExistInModule($modulPaths, $classPath);
    }

    private function getClassPath($modelName, $identifier="Model")
    {
        if (strpos($modelName, '/') === false) { return false; }

        if (substr_count($modelName, "/") == 1) {
            $exp = explode("/", $modelName);
            return $exp[0] . "/$identifier/" . $exp[1];
        } else {
            return false;
        }
    }

    private function checkIfFileExistInModule($modulPaths, $modelname)
    {
        foreach($modulPaths as $path) {
            $path = $path . DS . $modelname . ".php";
            if (file_exists($path)) {
                return $path;
            }
        }

        return "0";
    }

}

Это прекрасно работает ... теперь актуальный вопрос.

Если я пишу ...

$obj = Main::getHelper("Property/Property");
$obj->

... тогда моя IDE (NetBeans) не предлагает автоматически открытые методы / свойства, которые я могу использовать.

Есть ли способ "научить" мою логику добавить автоматическое предложение / автоматическое завершение, чтобы оноавтоматически показывает все открытые методы / свойства, доступные в объекте?

1 Ответ

2 голосов
/ 24 сентября 2019

Вам нужно использовать блоки phpdoc .Уверены, что они поддерживаются NetBeans:

/** @var Property_Helper_Property $obj */
$obj = Main::getHelper("Property/Property");

С этого момента автоматическое завершение и статический анализ будут работать, поскольку будет понятно, что $obj будет экземпляром Property_Helper_Property. * 1008.*

...