As to the last part, I was in the same situation as you about a year ago. I had been doing procedural PHP scripts for about ten years and didn’t understand much at all about OOP, namespaces, let alone things like type hinting, PSR-#, DICs, etc. I’ve learned quite a bit over the past year or so. Looking back on code I wrote just 18 months ago looks like a tangled spaghetti mess that I hope nobody else ever sees.
In your Header_footer
middleware class, you can only type hint an object (Request $request
) if PHP knows what Request
is. That is where the use
statements come in. Think of them similar to PHP’s require
or import
functions, but more like how an alias works on Macs or a shortcut works on Windows. Basically you need to tell PHP what object (class) Request
is.
use Psr\Http\Message\ServerRequestInterface as Request;
use Psr\Http\Message\ResponseInterface as Response;
So we’re telling PHP that anytime we typehint Request
we really mean that the $request
is an instance of Psr\Http\Message\ServerRequestInterface
.
The error you see is because you didn’t explicitly tell the invoke method what Request
was. Since you didn’t tell it, it assumes that it is a class within the same namepace, in this case App\Middleware
, so it assuming Request
can be found in App\Middlware\Request
.
Some resources if you would like to get up to speed on newer PHP conventions…
- Object-Oriented Bootcamp (Laracasts)
- PHP: The Right Way (largely written by the guy who started Slim)