shahriar-siraj / vanilla-php-framework

Simple & lightweight framework built with raw PHP without using any external packages
34 stars 10 forks source link

404 - Not Found #2

Open rizwanrajput opened 3 years ago

rizwanrajput commented 3 years ago

Trying to run the script but giving this error: Notice: Trying to get property 'path' of non-object in D:\xampp\htdocs\vanilla-php-framework\app\Helpers\Route.php on line 106

Can anyone help?

shahriar-siraj commented 2 years ago

@rizwanrajput Extremely sorry for the late reply. But if you're still having the issue, how does your app/routes.php file look?

Siempouwels commented 1 year ago

This is very late but I fixed the errors.

By adding the route bellow to the routes.php

Route::get('/index.php', 'HomeController@index');

And fixed the error: Trying to get property 'path' of non-object by changing the handle function like bellow

public static function handle($path) { $desired_route = null;

    foreach (self::$routes as $route) {
        $pattern = $route->path;
        $pattern = str_replace('/', '\/', $pattern);

        $pattern = '/^' . $pattern . '$/i';
        $pattern = preg_replace('/{[A-Za-z0-9]+}/', '([A-Za-z0-9]+)', $pattern);

        if (preg_match($pattern, $path, $match)) {
            $desired_route = $route;
            break;
        }
    }

    if ($desired_route) {
        $url_parts = explode('/', $path);
        $route_parts = explode('/', $desired_route->path);

        foreach ($route_parts as $key => $value) {
            if (!empty($value)) {
                $value = str_replace('{', '', $value, $count1);
                $value = str_replace('}', '', $value, $count2);

                if ($count1 == 1 && $count2 == 1) {
                    Params::set($value, $url_parts[$key]);
                }
            }
        }

        if ($desired_route->method != strtolower($_SERVER['REQUEST_METHOD'])) {
            http_response_code(404);
            echo '<h1>Route Not Allowed</h1>';
            die();
        } else {
            $actions = explode('@', $desired_route->action);
            $class = '\\App\\Controllers\\' . $actions[0];
            $obj = new $class();
            echo call_user_func(array($obj, $actions[1]));
        }
    } else {
        http_response_code(404);
        echo '<h1>404 - Not Found</h1>';
        die();
    }
}

I hope this works for you @rizwanrajput
Thanks btw for sharing this code @shahriar-siraj
This is very usefull for small school projects