Search code examples
phproutesklein-mvc

How to serve static files using Klein.php


I'm trying to serve static files located in /web directory using Klein.php like this :

$klein->respond('/web/[*]', function($request, $response, $service, $app) {
    return $service->file(__DIR__ . $request->pathname());
});

But receive this error on the terminal

[Sat Jun 14 18:14:25 2014] PHP Fatal error: 
 Call to undefined method Klein\ServiceProvider::file()
 in /home/youssef/Desktop/gestion-stages/front_controller.php on line 50

Solution

  • Try this:

    $klein->respond('/web/[*]', function($request, $response, $service, $app) {
        return $response->file(__DIR__ . $request->pathname());
    });
    

    Looks like file() is a method of Response, rather than ServiceProvider:

    https://github.com/chriso/klein.php/blob/737e7268f5c3fdc6d6f1371cb2ee0264892e8540/src/Klein/Response.php#L85

    Klein is a great little framework, but I do find I have to dig into the source occasionally. On the bright side, the source has great comments and clean code. It's the sort of project the reading of which makes you a better programmer.

    The main dev is usually pretty good about responding to issues on GitHub if you have trouble with anything: https://github.com/chriso/klein.php/issues?state=open

    Another Option

    One final thing I should note. If this is what you're really trying to do, rather than a simplified example, you may be able to accomplish the same thing with Apache mod_rewrite, or the equivalent in Nginx, and have better performance, since you're not executing any PHP code at that point. On the other hand, if you want to do something more advanced, like checking the user's login credentiails before deciding whether to serve the file, or serve files outside your document root, the way you're doing it is probably spot on.

    I'm not very good at writing mod_rewrite rules, but I think you could do something like:

    RewriteRule ^/web/(.+) /your/desired/path/$1 [R,L]
    

    assuming the destination is web-accessible. Reference: http://httpd.apache.org/docs/2.2/rewrite/remapping.html

    Or, if it's not web-accessible, it looks like you could setup an alias: http://httpd.apache.org/docs/2.2/urlmapping.html#outside

    I haven't tested the rewrite rule, and I've never messed with aliases, but I think those will do the trick. Of course, this all assumes you are using Apache, have access to Apache configs, or at least .htacces config, and that you don't have a much grander scheme in mind than simply serving static files. I'm also assuming you are somewhat familiar with Apache config in general, which I know not everyone is. However, if that seems like it might work, give it a try. Or feel free to ignore it.