(codeigniter/Neo4j) PHP : 命名空间和自动加载器

(codeigniter/Neo4j) PHP : namespace and autoloader

当我尝试在 codeigniter (v2.2.x) 中安装 Neo4jPHP 库时,我遇到了有关名称空间的恼人问题。我已经搜索了 4 个小时没有成功。

简而言之,有一个libraries 目录,Neo4jPHP 必须复制到这个目录中。所以在'libraries/'中,有一个目录'Everyman/Neo4j/',里面包含了所有的Neo4j php classes.

此外,在同一个 'libraries' 目录中,有一个 class 具有自动加载器功能,旨在加载 Neo4j classes(在 'Everyman/Neo4j/').

'libraries'

里面
- libraries/
     |-- Everyman/
             |-- Neo4j/
                   |-- Client.php
                   |-- some_other_classes.php
     |-- Neo4j.php

然后,在我的代码中的某个地方,在全局命名空间中,我尝试实例化 class 客户端:

$client = new Client();

但是我收到错误 Class 'Client' not found.

在 class 客户端中,指定了以下命名空间:Everyman\Neo4j.

我必须承认我找到了 2 个解决此问题的方法:

在调用代码中,使用完全限定名称:

new Everyman\Neo4j\Client();

或者,在 Client.php 中删除命名空间。

在这两种情况下,它有效。但是,我想用这两个条件调用 Client class: 1. 我不想修改 Neo4jPhp 库中的任何内容。 2. 我真的不想使用完全限定名称 (Everyman\Neo4j\Client)。我想使用 "new Client()".

你们知道我如何实现这个吗(是的,我对命名空间和加载器没有很深入的了解)。

在Neo4j.php(带有加载程序的文件)

 <?php
    class Everyman{

    public function __construct()
    {
        spl_autoload_register(array($this,'autoload'));
    }

    public function autoload($sClass){
            $sLibPath = __DIR__.DIRECTORY_SEPARATOR;
    //Below, i modified the instruction so that the class file
    //can be found. However, the class is not found.
            $sClassFile = 'Everyman'.DIRECTORY_SEPARATOR.'Neo4j'.str_replace('\',DIRECTORY_SEPARATOR,$sClass).'.php';
            $sClassPath = $sLibPath.$sClassFile;
            if (file_exists($sClassPath)) {
                require($sClassPath);
            }
        }
    }

就是这样。我想我已经把我所有的信息都给你了。如果没有人可以帮助我,我将不得不使用 'new Everyman\Ne4j\Client();' (有效)。

寻求帮助似乎很愚蠢,因为我已经找到了 2 个解决方法,但我真的很想学习如何正确处理这个问题(如果可能的话)。

谢谢。

好像$client = new Everyman\Neo4j\Client('localhost', 7474);这样的代码是官方用法:https://github.com/jadell/neo4jphp#connection-test

所以这不是变通办法。

I really don't want to have to use the fully qualified name (Everyman\Neo4j\Client). I want to use "new Client()".

我不知道你真正想要什么。但是,如何将下面的代码放入您使用的代码中 Everyman\Neo4j\Client:

use Everyman\Neo4j\Client;

$client = new Client();

http://php.net/manual/en/language.namespaces.importing.php

支持的安装 neo4jphp 的方式是使用 Composer (https://getcomposer.org/)。学习如何使用 Composer 是个好主意,因为可以使用它安装大量 PHP 库。它还会为您设置自动加载,因此您不必自己担心路径和名称空间。

如果你不想每次都写new Everyman\Neo4j\Client(),你可以在脚本的顶部放一个use语句:use Everyman\Neo4j\Client;然后是new Client();

感谢您的回答。 由于某种原因,'use Everyman\Neo4j\Client' 命令没有起作用,我决定不对这个问题进行进一步的调查。

所以我决定继续调用“$client = new Everyman\Neo4J\Client();”,而不是尝试实现“$client = new Client();”。

感谢您的建议。

Loïc.