0

I registering a controller with the container, but it seems not working because it doesn't match to the correct location.

\slim\src\routes.php

<?php
// Routes
$app->get('/dd', 'App\controllers\HomeController:home');

\slim\App\controllers\HomeController.php

<?php
class HomeController 
{
   protected $container;

   // constructor receives container instance
   public function __construct(ContainerInterface $container) {
       $this->container = $container;
   }

   public function home($request, $response, $args) {
        // your code
        // to access items in the container... $this->container->get('');
        return $response;
   }

   public function contact($request, $response, $args) {
        // your code
        // to access items in the container... $this->container->get('');
        return $response;
   }
}

My project folder structure:

\slim
  \public
    index.php
    .htaccess

  \App
    \controllers
      HomeController.php

  \src
    dependencies.php
    middleware.php
    routes.php
    settings.php

  \templates
    index.phtml

  \vendor
    \slim

Maybe I should to setting \slim\src\settings.php?

Because it show Slim Application Error:

Type: RuntimeException Message: Callable App\controllers\HomeController does not exist File: D:\htdocs\slim\vendor\slim\slim\Slim\CallableResolver.php Line: 90

Last, I also refer to these articles: https://www.slimframework.com/docs/objects/router.html#container-resolution

PHP Slim Framework Create Controller PHP Slim Framework Create Controller

How can i create middleware on Slim Framework 3? How can i create middleware on Slim Framework 3?

kkasp
  • 113
  • 1
  • 9

1 Answers1

0

Add psr-4 to your composer file so that you're able to call your namespaces.

{
    "require": {
        "slim/slim": "^3.12
    },
    "autoload": {
        "psr-4": {
            "App\\": "app"
        }
    }
}

This PSR describes a specification for autoloading classes from file paths. Then in your routes.php file add this at the top :

<?php
    use app\controllers\HomeController;
    // Routes
    $app->get('/dd', 'App\controllers\HomeController:home');

and finally in your HomeController.php file add :

<?php
    namespace app\controllers;
    class HomeController 
    {
    //.. your code
    }

hope this helps...:)

bloo
  • 1,416
  • 2
  • 13
  • 19