daveh / php-mvc

A simple PHP model-view-controller framework, built step-by-step as part of the "Write PHP like a pro: build an MVC framework from scratch" course on Udemy.
https://davehollingworth.com/go/phpmvc/
MIT License
782 stars 311 forks source link

Router confusion for multiple controllers #100

Closed pf-tech closed 2 years ago

pf-tech commented 2 years ago

Hello.

I'm getting a 404 when trying to access a controller NOT named Home.php

File structure --php-mvc -- --App -- -- --Controllers -- -- -- -- Home.php -- -- -- -- Timbrel.php -- --Models -- --Views -- -- --Home -- -- -- --index.html -- -- --Timbrel -- -- -- --index.html -- --Core -- --logs -- --public -- -- --css -- -- --js -- -- --index.php

In index.php I've got two add route actions plus the "catch-all" at the very bottom (I added the $url = trim($url, '/').'/'; to the Router.php from someone else's comment)

//HOME INDEX ROUTE IS DEFAULT $router->add('/', ['controller' => 'Home', 'action' => 'index']); <--works fine for www.my-domain.com

//NEW CONTROLLER THAT DOESN'T WORK... (top version is my most current version but I've tried many other configurations. Some are listed below.) $router->add('timbrel/index', ['controller' => 'Timbrel', 'action' => 'index', 'namespace' => 'Timbrel']); <--current I've also tried $router->add('timbrel/', ['controller' => 'Timbrel', 'action' => 'index', 'namespace' => 'Timbrel']); I've also tried $router->add('', ['controller' => 'Timbrel', 'action' => 'index', 'namespace' => 'Timbrel']); <--this renders but overwrites Home.php action.

In App->Controllers->Timbrel.php I have an indexAction that calls the template View::renderTemplate('Timbrel/index.html', [ 'name' => 'Dave', 'colours' => ['red', 'green', 'blue'] ]);

When I go to www.my-domain.com The index page "Home/index.html" renders just fine which I expected.

When I go to www.my-domain.com/timbrel/index OR www.my-domain.com/timbrel/ OR www.my-domain.com/timbrel/index.html OR www.my-domain.com/timbrel I receive 404 Not found.

What am I doing wrong?

Thanks!

daveh commented 2 years ago

Hi - does it work if you do this: www.example.com/index.php?timbrel/index

If so, the URL rewriting isn't working. Check you have the mod_rewrite module enabled in Apache.

Your code looks fine, so if it's not that, I would try debugging it by printing out various stages of the match method, e.g. the $url argument, the contents of the routes array etc. e.g. var_dump($url); to see where the problem might be.

pf-tech commented 2 years ago

That was it. Thank you so much for the hint!

I saw this in the nginx config file if ($rule_0 = "21"){

Should that be if ($rule_0 == "21"){ or do the rewrite rules not have assigned in the same way as a language like PHP?

Thanks!

daveh commented 2 years ago

The comparison operator in an nginx rewrite rule is =. This is nginx code and is different to PHP. Relevant documentation is here.