Slim4 : Why doesn't it work?

I went through the tutorial (http://www.slimframework.com/2019/04/25/slim-4.0.0-alpha-release.html) for V4 and following the steps to install and run a small application… but got stuck at the very 1st stage where it has been written…
composer require slim/slim “^4.0”
There is no stable version yet, so how will it work?
So, as composer suggested to chose 4.0.0-alpha/4.0.0-beta/4.x-dev, I chose 4.x-dev and that never exists. Then I tried 4.0.0-alpha (composer require slim/slim “^4.0.0-alpha”) and same got installed well and I install slim psr7 using composer require slim/psr7:dev-master which was flawless!
Then I tried s simple example (as given in the tutorial)
<?php
use Psr\Http\Message\ResponseInterface as Response;
use Psr\Http\Message\ServerRequestInterface as Request;
use Slim\Factory\AppFactory;
use Slim\Middleware\ErrorMiddleware;
use Slim\Middleware\RoutingMiddleware;

require DIR . ‘/vendor/autoload.php’;

$app = AppFactory::create();

$app->get(’/’, function (Request $request, Response $response, $args) {

  • $response->getBody()->write(“Hello world!”);*
  • return $response;*
    });

$app->run();
Which ended up with error!
And this as well…
<?php
use Psr\Http\Message\ResponseInterface as Response;
use Psr\Http\Message\ServerRequestInterface as Request;
use Slim\Factory\AppFactory;
use Slim\Middleware\ErrorMiddleware;
use Slim\Middleware\RoutingMiddleware;

require DIR . ‘/vendor/autoload.php’;

$app = AppFactory::create();

/*

    • The routing middleware should be added earlier than the ErrorMiddleware*
    • Otherwise exceptions thrown from it will not be handled by the middleware*
  • /
    $routeResolver = $app->getRouteResolver();
    $routingMiddleware = new RoutingMiddleware($routeResolver);
    $app->add($routingMiddleware);

/*

    • The constructor of ErrorMiddleware takes in 5 parameters*
    • @param CallableResolverInterface $callableResolver -> CallableResolver implementation of your choice*
    • @param ResponseFactoryInterface $responseFactory -> ResponseFactory implementation of your choice*
    • @param bool $displayErrorDetails -> Should be set to false in production*
    • @param bool $logErrors -> Parameter is passed to the default ErrorHandler*
    • @param bool $logErrorDetails -> Display error details in error log*
    • which can be replaced by a callable of your choice.*
    • Note: This middleware should be added last. It will not handle any exceptions/errors*
    • for middleware added after it.*
  • /
    $callableResolver = $app->getCallableResolver();
    $responseFactory = $app->getResponseFactory();
    $errorMiddleware = new ErrorMiddleware($callableResolver, $responseFactory, true, true, true);
    $app->add($errorMiddleware);

$app->get(’/’, function (Request $request, Response $response, $args) {

  • $response->getBody()->write(“Hello world!”);*
  • return $response;*
    });

$app->run();
The only difference was the formation of the error was good for eyes but not good for the understanding!
So, why someone will use Slim4 when the tutorial itself guides wrong installation?
Developer can’t execute a simple script even after fixing the installation by his own!
And very surprisingly, you people haven’t covered this error anywhere… :roll_eyes::roll_eyes::roll_eyes::roll_eyes:
Type: Slim\Exception\HttpNotFoundException

Code: 404

Message: Not found.

File: C:\xampp\htdocs\vinpro\slim\vendor\slim\slim\Slim\Middleware\RoutingMiddleware.php

Line: 82

Make sure your .htaccess is available.
For running your slim 4 app in sub-directory consider using

$app->setBasePath(‘slim-app-path’);

So, why someone will use Slim4 when the tutorial itself guides wrong installation?

The link you have used is just a(outdated) release news about Slim 4 alpha. Better use the documentation for Slim 4: Slim 4 Documentation - Slim Framework

And very surprisingly, you people haven’t covered this error anywhere…

You are not the first person who gets this error message. I am sure you will find something about this topic here in the forum. :wink:

Hi,

None of the suggestion provide in this forum resolved this issue, we have tested all the solution and even we have changed our existing project structure but no luck as we are hitting this issue when we call the custom middleware. Below is the entire project structure and configuration, the below configuration are built with bit and pieces if information collected from this fourm

Configuration Details
container.php

<?php

use Psr\Container\ContainerInterface;
use Slim\App;
use Slim\Factory\AppFactory;
use Slim\Middleware\ErrorMiddleware;
use Slim\Views\Twig;
use Selective\Config\Configuration;
use Psr\Http\Message\ResponseFactoryInterface;
use Selective\BasePath\BasePathMiddleware;

return [
    ResponseFactoryInterface::class => function (ContainerInterface $container) {
        return $container->get(App::class)->getResponseFactory();
    },

    Configuration::class => function () {
        return new Configuration(require __DIR__ . '/settings.php');
    },

    App::class => function (ContainerInterface $container) {
        AppFactory::setContainer($container);
        $container->set('view', function() { return Twig::create('../tpl', ['cache' => false]); });
        $app = AppFactory::create();
        return $app;
    },

    ErrorMiddleware::class => function (ContainerInterface $container) {
        $app = $container->get(App::class);
        $settings = $container->get(Configuration::class)->getArray('error_handler_middleware');

        return new ErrorMiddleware(
            $app->getCallableResolver(),
            $app->getResponseFactory(),
            (bool)$settings['display_error_details'],
            (bool)$settings['log_errors'],
            (bool)$settings['log_error_details']
        );
    },

    BasePathMiddleware::class => function (ContainerInterface $container) {
        return new BasePathMiddleware($container->get(App::class));
    },

];

middleware.php

<?php

use Slim\App;
use Slim\Views\TwigMiddleware;
use Selective\Config\Configuration;
#use Selective\BasePath\BasePathMiddleware;
use Slim\Middleware\RoutingMiddleware;
use Slim\Middleware\ErrorMiddleware;
use App\Authendication\AuthMiddleware;

return function (App $app) {
       $routingMiddleware = new Slim\Middleware\RoutingMiddleware(
                $app->getRouteResolver(),
                $app->getRouteCollector()->getRouteParser()
       );
       $app->add(TwigMiddleware::createFromContainer($app));
       $app->addBodyParsingMiddleware();
       $app->add(AuthMiddleware::class);
       $app->addRoutingMiddleware();
       $app->add(BasePathMiddleware::class);
       $app->add(ErrorMiddleware::class);
};
?>

Auth middleware

<?php
namespace App\Authendication;
define("ROOT_PATH", 'https://'.$_SERVER['HTTP_HOST']);
use Psr\Http\Message\ResponseFactoryInterface;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface;
use Psr\Http\Server\RequestHandlerInterface;
use Slim\Routing\RouteContext;
use Nyholm\Psr7\Factory\Psr17Factory;
use Psr\Http\Server\MiddlewareInterface;

final class AuthMiddleware implements MiddlewareInterface {
      private $responseFactory;
      public function __construct(ResponseFactoryInterface $responseFactory) { $this->responseFactory = $responseFactory; }
      public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface {
                      $routeContext = RouteContext::fromRequest($request);
                      $route = $routeContext->getRoute();
                      if(empty($route)) { throw new NotFoundException($request, $response); }
                      $routeName = $route->getName();
                      $publicRoutesArray = array('f401');
                      if(empty($_SESSION['user']) && in_array($routeName, $publicRoutesArray)) {
                          $routeParser = RouteContext::fromRequest($request)->getRouteParser();
                          $url = $routeParser->urlFor('login');
                           return $this->responseFactory->createResponse()->withHeader('Location', ROOT_PATH.$url)->withStatus(302);
                      } else { return $handler->handle($request); }
      }
}

?>```
**Project Structure**

Document Root : /var/www/Slim4/public
Inside the folder “public” we have the below folder and files

  • index.php
  • .htaccess
  • static - folder
    And the entry in the file “htaccess” is as below
  • RewriteEngine On
  • #RewriteBase /
  • RewriteCond %{REQUEST_FILENAME} !-f
  • RewriteCond %{REQUEST_FILENAME} !-d
  • RewriteRule ^ index.php [QSA,L]

Project Folder : /var/www/Slim4
The project folder contains the folders and files “composer.json, composer.lock, .htaccess, config, php-fcgi-scripts, public, source, ssl, temp. tpl, vendor”.
And the file content of the file “.htaccess” is as below

  • RewriteEngine on
  • RewriteRule ^$ public/ [L]
  • RewriteRule (.*) public/$1 [L]