Search code examples
phpfat-free-framework

Fat-free php invalid route


I'm currently having a routing issue with the fat-free framework. After looking around and reading the documentation I've so far been unable to solve it despite it seeming to be a simple problem.

I'm using f3's standard routing format from the root directory:

$f3->route(array('GET /', 'GET /index.php'), function($f3) {
    include 'header.html';
    include 'Home/index.html';
    include 'footer.html';
});

//search
$f3->route('GET /Browse', function() {
    include 'Browse/index.html';
});

These routes both work correctly and as expected. When I enter localhost on xammp, both return the pages outlined. Both have a file structure:

-Root
-index.php
-header.html
-footer.html
--Browse
---index.html

After defining a new route I do not wish to have a folder with a index.html file and instead respond by echoing html.

$f3->route('GET /Latest',
    function() {
        include 'submit/index.html';
        echo 'This is our home page.';
    }
);

When I use the code above, and go to localhost/Latest I'm presented with:

Error 404 : Not found

My question is how can I allow a response directly from PHP without having a subsequent folder and index.html file.

Thanks and many regards :)


Solution

  • You're probably looking for the framework template engine.

    There are various ways to structure your code, but here's a quick basic example:

    // index.php
    
    $f3->UI='templates/';
    
    $f3->route('GET /home',function($f3){
        $f3->main='home.html';
        $f3->title='Homepage';
        $tpl=Template::instance();
        echo $tpl->render('layout.html');
    });
    
    $f3->route('GET /contact',function($f3){
        $f3->main='contact.html';
        $f3->title='Contact us';
        $f3->address='5578 Grant Street Woodbridge, VA 22191';
        $tpl=Template::instance();
        echo $tpl->render('layout.html');
    });
    
    <!-- templates/layout.html -->
    <!DOCTYPE html>
    <title>{{ @title }}</title>
    
    <body>
      <include href="header.html"/>
      <main>
        <include href="{{ @main }}"/>
      </main>
      <include href="footer.html"/>
    </body>
    
    <!-- templates/home.html -->
    <h1>Hey hey! Welcome home!</h1>
    
    <!-- templates/contact.html -->
    <h1>Our address</h1>
    <p>{{ @address }}</p>
    

    As for the 404 error, make sure your .htaccess file is correctly configured, especially the RewriteBase directive. If it's not, every URI other than / will throw a 404. See here for more details about the setup.