Coder Social home page Coder Social logo

simple-mvc-php-framework's Introduction

Simple MVC PHP Framework

Requirements

PHP >=7.1.20 Composer

Tested on

PHP 7.1.20 Apache

Installation

git clone https://github.com/gmaccario/simple-mvc-php-framework.git

Or download the package from Github.

Composer

After the installation on your local or container, run the following command:

composer install

On your own:

  1. Set up and run your webserver (e.g. Apache);
  2. Open your browser;
  3. Go to the index page (often localhost).

Note: if you decide to put the framework into a subfolder, open /config/config.php and set up the name of the subfolder here URL_SUBFOLDER

Simple MVC PHP Framework Tutorial

https://www.giuseppemaccario.com/how-to-build-a-simple-php-mvc-framework/

NOTE: The goal of the article above, is to explain how to implement a simple MVC using PHP, not to explain the SOLID principles. So, in this context, I will mix the model context with the database access.

simple-mvc-php-framework's People

Contributors

gmaccario avatar informagico avatar warrickrandi avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar

simple-mvc-php-framework's Issues

routing not working

Hi, i followed your guide to create. It showed route issue. So i downloaded your code and tried. It kept showing routes issues. I put the project in xampp/htdocs. Kindly assist
image

Correct way to POST Data

Hello, first of all excellent work with this project, it is very clean and explanatory. I have created the following code in Router.php to be able to make POST requests, however I don't know if it is the correct way to do it:

`class Router
{
public function __invoke(RouteCollection $routes)
{
$messageError = null;
$auth = new Auth();
$context = new RequestContext();
$request = Request::createFromGlobals();
$context->fromRequest(Request::createFromGlobals());

    $matcher = new UrlMatcher($routes, $context);
    try {
        $matcher = $matcher->match($context->getPathInfo());

        array_walk($matcher, function(&$param)
        {
            if(is_numeric($param)) 
            {
                $param = (int) $param;
            }
        });

        $controller = $matcher["controller"][0];

        $action = $matcher["controller"][1];

        $controllerInstance = new $controller();


        if($context->getMethod() === $matcher["methods"][0]){



        if(isset($matcher["condition"])){
            
         if($matcher["condition"] === "token"){

         if(!$auth->checkToken($request->get('token'))){


            throw new SessionNotFoundException("unauthorized");

         }


         }


        }


        if($matcher["methods"][0]==="GET")
        $params = array_merge(array_slice($matcher, 2, -1), array('routes' => $routes));
        else
        $params = array_merge(array($request), array('routes' => $routes));



        }
        else{

         throw new MethodNotAllowedException(array());
         
        }

        call_user_func_array(array($controllerInstance, $action), $params);

    } catch (MethodNotAllowedException $e) {

        $messageError = 'Route method is not allowed.';

    } catch (ResourceNotFoundException $e) {

        $messageError = 'Route does not exists.';

    } catch (NoConfigurationException $e) {

        $messageError = 'Configuration does not exists.';

    } catch (SessionNotFoundException $e) {

        $messageError = 'Session not found, unauthorized';

    }
    
    if(isset($messageError)){

         
        $aceResponse = new AceResponse();
        $aceResponse->setResponse("0" ,array("error"=>$messageError));          
        $response = new Response();
        $response->setContent(json_encode($aceResponse->getResponse()));
        $response->setStatusCode(Response::HTTP_OK);
        $response->headers->set('Content-Type', 'application/json');

        $response->send();
    }

}

}

// Invoke
$router = new Router();
$router($routes);
My web.php
use Symfony\Component\Routing\Route;
use Symfony\Component\Routing\RouteCollection;
use App\Controllers\SkinWebController;

$routes = new RouteCollection();

$routes->add('SKIN',
new Route(constant('URL_SUBFOLDER') . '/skin/{request}',
array('controller' => [SkinWebController::class, 'showViewAction'],
'methods'=>['GET']),
array('request' => '[a-zA-Z0-9-]+')));

$routes->add('GET_SKIN_THEME',
new Route(constant('URL_SUBFOLDER') . '/ace/getSkinTheme',
array('controller' => [SkinWebController::class, 'getSkinThemeAction'],
'methods'=>['POST'], 'condition'=>'token'),
array()));`

And my SkinWebController.php

`class SkinWebController
{

public function showViewAction(string $request, RouteCollection $routes)

{
  
    $skin = new SkinWeb();
    $auth = new Auth();
    $skin->setFormToken($auth->generateToken());
    $skin->setIdRequest($request);
    $skin->setUrl(constant("API_PHP"));

    require_once APP_ROOT . '/views/skinWeb.php';

}

public function getSkinThemeAction(Request $request, RouteCollection $routes)
{

    $response = new Response();

    $api = new AceWebMethods();
    $payload = json_decode($request->get('payload')); 
    
    $result = $api->getSkinTheme($payload);

    $response->setContent(json_encode($result->getResponse()));
    $response->setStatusCode(Response::HTTP_OK);
    $response->headers->set('Content-Type', 'application/json');

    $response->send();
    
}

}`

How can I configure to send json data to the api ?
Actually can only send form-data type. Thanks very much.

Autoloader not working

When i try to request the homepage an error occurs in Router.php
Cant find \App\Controllers\PageController
$className = '\\App\\Controllers\\' . $matcher['controller']; $classInstance = new $className();
When the router try to instantiate the Controller class required.

HTTP ERROR 500

Hi,

thanks for your tutorial. Unfortunately i get an ERROR 500 on all existing routes:

  • Home
  • product/1

Other routes respond with "Route does not exists."

Thanks for your help,
Daniel

Static content response Route does not exists

I make file myfunctions.js in public folder and link it to html part of my car_list.php

<!DOCTYPE html>
<html>

<head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <meta name="description" content="">
    <meta name="author" content="">
    <link rel="shortcut icon" href="favicon.png">
    <title>Car Assist</title>

    <script src="myfunctions.js"></script>
</head>

I checked network trafic and I get "Route does not exists.".
My .htaccess file look like this:

<IfModule mod_rewrite.c>
RewriteEngine On

# Stop processing if already in the /public directory
RewriteRule ^public/ - [L]

# Static resources if they exist
RewriteCond %{DOCUMENT_ROOT}/public/$1 -f
RewriteRule (.+) public/$1 [L]

# Route all other requests
RewriteRule (.*) public/index.php?route=$1 [L,QSA]

Update to PHP8

Could you look at updating to PHP 8.2 or later, especially as PHP 7 is now EOL.

Route does not exists.

Nice to greet you,

I would like help with the following problem:

When I insert a file into the public folder, "Route does not exist." In this case the related files go inside the folder:

public/assets/
public/bootstrap/
public/plugins/
public/sass/

I thank you very much in advance if you can help me.

"Route does not exists." for static content

I tested out the error.
I placed the project to carassist URL_SUBFOLDER.
Please add script to views/product.php

<script src="public/js/car/car_edit.js></script>
place JavaScript in subfolder public/js/car/.

with js content for example

$(document).ready( function () {
    alert("page loaded");
} );

open http://localhost/carassist/product/1 in browser, and check if car_edit.js downloaded.

This relative path try access to http://localhost/carassist/product/public/js/car/car_edit.js
(where /product is left in the URL)
When I make a new route to http://localhost/carassist/product (without number path parameter, for example listing products)
$routes->add('product_list', new Route(constant('URL_SUBFOLDER') . '/product', array('controller' => 'ProductController', 'method'=>'listAction'), array()));

and set script in views/product_list.php
<script src="public/js/car/car_list.js></script>

http://localhost/carassist/public/js/car/car_list.js access URL produced for this relative path, which is correct now (there is no product subfolder what should left from route product/1).

I think rewrite rule in .htaccess make this error.
Please see my project on github based on your project:
https://github.com/pzoli/cars

POST request drop MethodNotAllowedException

if I make a Route with parameters POST request, Routers drop MethodNotAllowedException.

$routePostCar` = new Route(constant('URL_SUBFOLDER') . '/car/create', array('controller' => 'CarController', 'method'=>'createNewCar'), array(), array(), '', array(), 'POST');
$routes->add('car_create',$routePostCar);

In Router.php(43) I checked the allowed method:

echo 'Route method is not allowed. Allowed methods:' . json_encode($e->getAllowedMethods());

it returns ["POST"] :

If I check the method in the controller, I get 'POST'

use Symfony\Component\HttpFoundation\Request;

public function createNewCar(RouteCollection $routes) {
        $request = Request::createFromGlobals();
        $data = $request->getMethod();
        var_dump($data);
    }	

Route not found

Using your repository, have found that the http://HOSTNAME/product/1 URL results in a "URL not found".

Actions taken:

  • download repo zip file
  • extract to local server
  • install composer requirements
  • restart apache
  • visit site, navigate to the product page

Routes from file

Do you know solution how can I load router from YAML or JSON config file?

Unknown named parameter $routes in Router.php

PHP Fatal error:  Uncaught Error: Unknown named parameter $routes in [Root]\app\Router.php:43
Stack trace:
#0 [Root]\app\Router.php(43): call_user_func_array()
#1 [Root]\app\Router.php(57): App\Router->__invoke()
#2 [Root]\public\index.php(14): require_once('...')
#3 {main}
  thrown in [Root]\app\Router.php on line 43

The error above is clear. If you need more details ask me, please.
Maybe is the problem with __invoke method?

UPDATES: After testing session, I see the problem is in array_slice because if I move the 3rd argument from -1 to another number I receive other issues. Below the interested line:
$params = array_merge(array_slice($matcher, 2, -1), array('routes' => $routes));

The first issue is in $routes parameter, but my question is what are you expecting from $params variable? It seems you are assigning the wrong value to $params. @gmaccario

Reaching $route with "/" suffix causes ResourceNotFoundException

Hello,
I don't really know if this is normal behavior, an issue or whaterver, but I defined routes like this :

$path = '/admin/users/';
$routes->add('adminUsersList', new Route($path, ['controller' => 'Admin\UserController', 'method' => 'list']));

If I go to domain.com/admin/users/ it is ok, but if I remove the ending slash domain.com/admin/users I got an ResourceNotFoundException.
Vice versa with $path = '/admin/users';

Thanks!

I get an error

Deprecated: Return type of Symfony\Component\Routing\RouteCollection::getIterator() should either be compatible with IteratorAggregate::getIterator(): Traversable, or the #[\ReturnTypeWillChange] attribute should be used to temporarily suppress the notice in F:\xampp\htdocs\pascalservices-website\vendor\symfony\routing\RouteCollection.php on line 54

Deprecated: Return type of Symfony\Component\Routing\RouteCollection::count() should either be compatible with Countable::count(): int, or the #[\ReturnTypeWillChange] attribute should be used to temporarily suppress the notice in F:\xampp\htdocs\pascalservices-website\vendor\symfony\routing\RouteCollection.php on line 64
Route does not exists.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.