0

我正在做一个项目,但我有一个非常烦人的问题。我使用一个 PHP 文件 rb.php,其中包含项目的几个重要类(RedBean ORM 的文件 rb.php,合而为一)。问题是我可以在特殊位置正确使用文件,但不能在其他位置使用。

这是我的树状结构:

树状

当我去 index.php 时,一切顺利,我可以做到require('rb.php');

<?php

require_once 'vendor/autoload.php';
require('rb.php');
R::setup('mysql:host=localhost;
        dbname=silex','root','');
require('Model_Bandmember.php');

use Silex\Application;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;



$srcDir = __DIR__;
$app = new Application();
$app['debug'] = true;
$app->register(new DDesrosiers\SilexAnnotations\AnnotationServiceProvider(), array(
    "annot.controllerDir" => $srcDir."\controllers"
));

$app->register(new Silex\Provider\TwigServiceProvider(), array(
    'twig.path' => $srcDir.'\views',
));

    $bandmember = R::dispense('bandmember');
    $bandmember->name = 'Fatz Waller';
    $id = R::store($bandmember);
    $bandmember = R::load('bandmember',$id);
    R::trash($bandmember);
    echo $lifeCycle;die();
$app->run();

我有 $lifeCycle 的良好价值。但我想在控制器中使用这个文件来实现 add()、updates() 等功能。所以我试试这个:

<?php

namespace App\Controllers;
use DDesrosiers\SilexAnnotations\Annotations as SLX;
use Silex\Application;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
require(__DIR__.'/../rb.php');
/**
 * @SLX\Controller(prefix="article")
 */
class ArticleController
{

    /**
     * @SLX\Route(
     *      @SLX\Request(method="GET", uri="/"),
     *      @SLX\Bind(routeName="articleIndex")
     * )
     */
    public function index(Application $app)
    {
        $articles = R::findAll('article');
        return $app['twig']->render('Article/index.twig', array(
        'articles' => $articles,
        ));
    }
...
...

但我有这个错误:

Cannot redeclare class RedBeanPHP\RedException in C:\wamp64\www\SilexTest\rb.php on line 6737

很好,我认为该文件必须已经存在!但如果我评论它我有这个错误:

Class 'App\Controllers\R' not found

这是正常的,因为这个类在我刚刚评论的 rb.php 文件中。

如果我做一个要求,我有一个类 redeclare ,但如果我不放它,它就没有一个类。任何帮助将不胜感激。

4

1 回答 1

2

由于rb已经包含,因此无需在任何地方包含它。要在全局范围内使用它,您必须使用\R

$articles = \R::findAll('article');

因为,看起来好像R是在全局范围内可用。在这种情况下,您可以use R;在班级顶部使用,例如:

namespace App\Controllers;

use DDesrosiers\SilexAnnotations\Annotations as SLX;
use Silex\Application;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use R; // <-- Notice this

/**
 * @SLX\Controller(prefix="article")
 */
class ArticleController
{
    // Use: R::findAll('article') in any method in this class
}

应该阅读.PHP

于 2016-12-27T23:42:50.340 回答