# Slim4 : Why doesn't it work?

**URL:** <https://discourse.slimframework.com/t/slim4-why-doesnt-it-work/3209>\
**Category:** Questions\
**Created:** [June 6, 2019, 6:02am UTC](https://discourse.slimframework.com/t/slim4-why-doesnt-it-work/3209 "2019-06-06T06:02:56Z")\
**Posts on this page:** 5\
**Page:** 1

<div class="post-metadata">

**Author:** ![sagarsarkar](https://avatars.discourse-cdn.com/v4/letter/s/94ad74/32.png) [@sagarsarkar](https://discourse.slimframework.com/u/sagarsarkar)\
**Post date:** [June 6, 2019, 6:02am UTC](https://discourse.slimframework.com/t/slim4-why-doesnt-it-work/3209/1 "2019-06-06T06:02:56Z")

</div>

I went through the tutorial (_[http://www.slimframework.com/2019/04/25/slim-4.0.0-alpha-release.html](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… 🙄🙄🙄🙄  
**Type:** Slim\Exception\HttpNotFoundException

**Code:** 404

**Message:** Not found.

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

**Line:** 82

---

<div class="post-metadata">

**Author:** ![raziul](https://yyz2.discourse-cdn.com/flex030/user_avatar/discourse.slimframework.com/raziul/32/1161_2.png) [@raziul](https://discourse.slimframework.com/u/raziul)\
**Post date:** [May 4, 2020, 12:22pm UTC](https://discourse.slimframework.com/t/slim4-why-doesnt-it-work/3209/2 "2020-05-04T12:22:15Z")

</div>

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

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

---

<div class="post-metadata">

**Author:** ![odan](https://avatars.discourse-cdn.com/v4/letter/o/9de053/32.png) [@odan](https://discourse.slimframework.com/u/odan)\
**Post date:** [May 4, 2020, 12:59pm UTC](https://discourse.slimframework.com/t/slim4-why-doesnt-it-work/3209/3 "2020-05-04T12:59:46Z")

</div>

> 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](http://www.slimframework.com/docs/v4/)

> 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. 😉

---

<div class="post-metadata">

**Author:** ![Vino](https://avatars.discourse-cdn.com/v4/letter/v/c2a13f/32.png) [@Vino](https://discourse.slimframework.com/u/Vino)\
**Post date:** [May 23, 2020, 1:53pm UTC](https://discourse.slimframework.com/t/slim4-why-doesnt-it-work/3209/4 "2020-05-23T13:53:25Z")

</div>

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**

```auto
<?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**

```auto
<?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**

````auto
<?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]

---

<div class="post-metadata">

**Author:** ![Pictor13](https://yyz2.discourse-cdn.com/flex030/user_avatar/discourse.slimframework.com/pictor13/32/1684_2.png) [@Pictor13](https://discourse.slimframework.com/u/Pictor13)\
**Post date:** [May 10, 2025, 1:55pm UTC](https://discourse.slimframework.com/t/slim4-why-doesnt-it-work/3209/5 "2025-05-10T13:55:13Z")

</div>

The code seems ok.  
If a 404 error is returned, then Slim couldn’t match any of the defined routes.  
In my experience this is usually due to a missing `setBasePath` indicating the sub-directory at which the app is published; or due to some issue with the http-request Rewrite from the webserver (Apache here).

First check why the routing can’t match your defined route:  
add a debug command in `\Slim\Routing\FastRouteDispatcher::routingResults`, like

```auto
echo __METHOD__. 'Does '. $uri .' match any of ' . var_export($this->staticRouteMap, true); die;

```

it’s the fastest way to figure out what’s wrong (might be that the `REQUEST_URI` gets somehow manipulated by some rewrite and doesn’t match?).  
Go there, to the source of the issue. Trying trial & errors hoping the route-matching will be fixed is gonna waste a lot of time.
