0

I am learning how dependency injection works using this tutorial, and until this point, everything was working as expected. But after adding Routing, it starts to throw exceptions. I skipped to the next step and even tried to download the source codes from Github, but the issue still persists. Here is the exception I receive:

PHP Fatal error:  Uncaught DI\\Definition\\Exception\\InvalidDefinition: Entry "ExampleApp\\HelloWorld" cannot be resolved: the class doesn't exist
Full definition:
Object (
    class = #UNKNOWN# ExampleApp\\HelloWorld
    lazy = false
) in /var/www/html/vendor/php-di/php-di/src/Definition/Exception/InvalidDefinition.php:18
Stack trace:
#0 /var/www/html/vendor/php-di/php-di/src/Definition/Resolver/ObjectCreator.php(120): DI\\Definition\\Exception\\InvalidDefinition::create(Object(DI\\Definition\\ObjectDefinition), 'Entry "ExampleA...')
#1 /var/www/html/vendor/php-di/php-di/src/Definition/Resolver/ObjectCreator.php(71): DI\\Definition\\Resolver\\ObjectCreator->createInstance(Object(DI\\Definition\\ObjectDefinition), Array)
#2 /var/www/html/vendor/php-di/php-di/src/Definition/Resolver/ResolverDispatcher.php(64): DI\\Definition\\Resolver\\ObjectCreator->resolve(Object(DI\\Definition\\ObjectDefinition), Array)
#3 /var/www/html/vendor/php-di/php-di/src/Container.php(380): DI\\Definit in /var/www/html/vendor/php-di/php-di/src/Definition/Exception/InvalidDefinition.php on line 18

And this is my apache configuration:

<IfModule mod_ssl.c>
<VirtualHost 10.0.7.2:443>
    ServerAlias xyz.com
    DocumentRoot /var/www/html/public
    ServerName xyz.com

<Directory "/var/www/html/public">
    Options +FollowSymlinks
    RewriteEngine On
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteRule . index.php [QSA,L]
</Directory>

</VirtualHost>
</IfModule>

(Do not want to have .htaccess files, I can change httpd.conf file on my server).

Here is the public/index.php file:

declare(strict_types=1);

use DI\ContainerBuilder;
use ExampleApp\HelloWorld;
use FastRoute\RouteCollector;
use Middlewares\FastRoute;
use Middlewares\RequestHandler;
use Narrowspark\HttpEmitter\SapiEmitter;
use Relay\Relay;
use Zend\Diactoros\Response;
use Zend\Diactoros\ServerRequestFactory;
use function DI\create;
use function DI\get;
use function FastRoute\simpleDispatcher;

require_once dirname(__DIR__) . '/vendor/autoload.php';

$containerBuilder = new ContainerBuilder();
$containerBuilder->useAutowiring(false);
$containerBuilder->useAnnotations(false);

$containerBuilder->addDefinitions([
    HelloWorld::class => create(HelloWorld::class)
        ->constructor(get('Foo'), get('Response')),
    'Foo' => 'bar',
    'Response' => function() {
        return new Response();
    },
]);

/** @noinspection PhpUnhandledExceptionInspection */
$container = $containerBuilder->build();
$routes = simpleDispatcher(function (RouteCollector $r) {
    $r->get('/hello', HelloWorld::class);
});

$middlewareQueue[] = new FastRoute($routes);
$middlewareQueue[] = new RequestHandler($container);

/** @noinspection PhpUnhandledExceptionInspection */
$requestHandler = new Relay($middlewareQueue);
$response = $requestHandler->handle(ServerRequestFactory::fromGlobals());

$emitter = new SapiEmitter();
/** @noinspection PhpVoidFunctionResultUsedInspection */
return $emitter->emit($response);

And this is /src/HelloWorld.php:

namespace ExampleApp;

use Psr\Http\Message\ResponseInterface;

/**
 * @package   ExampleApp
 */
class HelloWorld
{
    private $foo;
    private $response;

    /**
     * @param ResponseInterface $response
     * @param string $foo
     */
    public function __construct(
        string $foo,
        ResponseInterface $response
    ) {
        $this->foo = $foo;
        $this->response = $response;
    }

    /**
     * @throws \RuntimeException
     * @throws \InvalidArgumentException
     */
    public function __invoke(): ResponseInterface
    {
        $response = $this->response->withHeader('Content-Type', 'text/html');
        $response->getBody()
            ->write("<html><head></head><body>Hello, {$this->foo} world!</body></html>");

        return $response;
    }
}

This is my composer.json file:

{
    "name": "myapp/platform",
    "description": "My test platform",
    "type": "project",
    "license": "Copyright",
    "require": {
        "php-di/php-di": "^6.0",
        "relay/relay": "^2.0",
        "zendframework/zend-diactoros": "^2.2",
        "middlewares/fast-route": "^1.2",
        "middlewares/request-handler": "^1.4",
        "narrowspark/http-emitter": "^1.0"
    },
    "autoload": {
        "psr-4": {
            "MineApp\\": "src/"
        }
    }
}

What is wrong with my configuration? How can I fix it?

Belkin
  • 199
  • 15
  • Instead of only linking to the tutorial you're going through, you need to post _your_ code (the relevant parts, like how you set up and use the DI container). Do you have a class called `HelloWorld` with the namespace `ExampleApp`? I also don't think your issue has anything to do with Apache. – M. Eriksson Nov 26 '19 at 17:46
  • Did you configure autoloading in composer.json? Or maybe you have a typo in a filename? Because PHP simply cannot find the class. – Matthieu Napoli Nov 26 '19 at 20:37
  • Here is my composer.json file: { "name": "my App/platform", "description": "My test platform", "type": "project", "license": "Copyright", "require": { "php-di/php-di": "^6.0", "relay/relay": "^2.0", "zendframework/zend-diactoros": "^2.2", "middlewares/fast-route": "^1.2", "middlewares/request-handler": "^1.4", "narrowspark/http-emitter": "^1.0" }, "autoload": { "psr-4": { "MineApp\\": "src/" } } } – Belkin Nov 26 '19 at 20:42
  • @MatthieuNapoli, do I need any special setting for PHP configuration? I assume PHP-DI takes care of autoloading for me, am I right? – Belkin Nov 26 '19 at 21:04
  • Your composer.json specifies autoloading for `MineApp\` but your code example uses the namespace `ExampleApp\`, this may be the source of the problem. – Matthieu Napoli Nov 27 '19 at 12:52
  • Fantastic! if you post it as your answer, I will make the conversation resolved. You are awesome! – Belkin Nov 27 '19 at 22:10

0 Answers0