3

I'm currently building a project to learn the Slim framework. I have a pretty good basic understanding of Slim but namespaces are still quite confusing to me. I'm storing my routes in separate files based on what page they relate to (home, about, add, etc). The issue is that I cannot create a Request or Response object without using

use \Psr\Http\Message\ServerRequestInterface as Request;
use \Psr\Http\Message\ResponseInterface as Response;

at the top of each route file. Is there a way I can put the use at the top of my main routes file and have every included file use it?

For example, my routes.php file is included in my start.php file which is included in my index.php. Inside my routes file has includes to each specific route home.php, about.php, add.php, etc. Each file included in my routes.php has to have a use statement otherwise I cannot access Response and Request without namespacing them.

Joe Scotto
  • 10,936
  • 14
  • 66
  • 136
  • No that isn't possible in PHP. See [SO Namespaces examples](http://stackoverflow.com/documentation/php/1021/namespaces), [PHP Docs](http://php.net/manual/en/language.namespaces.php), and [What are namespaces](http://stackoverflow.com/questions/3384204/what-are-namespaces/3384384#3384384). – Gerard Roche Sep 05 '16 at 21:45

1 Answers1

2

No, you can't do this. Rude explanation - "Use statement belongs to file" (In case we are not using multiplie namespace declarations in file, which is not recommended). Nor you can't extend namespace using require/include.

test.php: 
    include "MyString.php"; 
    print ","; 
    print strlen("Hello world!"); 
MyString.php: 
    namespace MyFramework\String; 
    function strlen($str) { 
        return \strlen($str)*2;
    } 
    print strlen("Hello world!");

Output: 24,12

But you can instantiate your objects once in the namespace. And they will be available in other files of the namespace.

test.php:
    namespace App;
    include "request.php";
    var_dump($request); //$request object is available here
request.php
    namespace App;
    use \Http\Request as Request;
    $request = new Request();

Also, there should be dependency container in Slim framework. Maybe you can put your objects here. Not familiar with the framework, so feel free to correct me.

Alexey Chuhrov
  • 1,787
  • 12
  • 25