Coder Social home page Coder Social logo

thecodeholic / php-mvc-framework Goto Github PK

View Code? Open in Web Editor NEW
462.0 30.0 173.0 93 KB

PHP MVC Framework

Home Page: https://www.youtube.com/playlist?list=PLLQuc_7jk__Uk_QnJMPndbdKECcTEwTA1

PHP 82.16% Hack 8.19% Shell 3.47% Dockerfile 6.18%
php php7 phpmvc mvc-framework-for-php

php-mvc-framework's Introduction

PHP MVC framework

Minimalistic custom framework created for educational purposes.

The framework is not well tested on production. If you use it on production you use it on your own risk.

Related core package: https://github.com/thecodeholic/tc-php-mvc-core


Installation

  1. Download the archive or clone the project using git
  2. Create database schema
  3. Create .env file from .env.example file and adjust database parameters (including schema name)
  4. Run composer install
  5. Run migrations by executing php migrations.php from the project root directory
  6. Go to the public folder
  7. Start php server by running command php -S 127.0.0.1:8080
  8. Open in browser http://127.0.0.1:8080

Installation using docker

Make sure you have docker installed. To see how you can install docker on Windows click here.
Make sure docker and docker-compose commands are available in command line.

  1. Clone the project using git
  2. Copy .env.example into .env (Don't need to change anything for local development)
  3. Navigate to the project root directory and run docker-compose up -d
  4. Install dependencies - docker-compose exec app composer install
  5. Run migrations - docker-compose exec app php migrations.php
  6. Open in browser http://127.0.0.1:8080

The project was created along with Youtube Video Series "Build PHP MVC Framework". I appreaciate if you share it.

php-mvc-framework's People

Contributors

thecodeholic 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  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  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

php-mvc-framework's Issues

AJAX Call

How do you do Ajax call on top of MVC? From what I can remember the last time I used Ajax on top of DIY MVC framework I always get html contents instead of JSON data. Note that I tried the json_encode from the server side and JSON.parse on the front end but I'm getting an error. I could get data only if the data needed is embedded on the views file then extract it using selectors on the front end. I'm looking for a solution where the MVC can return JSON data directly after AJAX call.

Fatal error: primaryKey()

Fatal error: Uncaught Error: Non-static method thecodeholic\phpmvc\db\DbModel::primaryKey() cannot be called statically in C:\wamp64\www\link\vendor\thecodeholic\php-mvc-core\Application.php on line 54

obraz

PHP 8.0: Calling non-static class methods statically result in a fatal error

Php8 does not accept
$app->router->post('/contact', [SiteController::class, 'handleContact']);

It accepts
$app->router->post('/contact', [new SiteController(), 'handleContact']);

The problem occurs if you are building the framework following the steps in the video. It is solved later in Router->resolve()

Uncaught TypeError: call_user_func_array(): Argument #1 ($callback) must be a valid callback, no array or string given in class-wp-hook.php:308

Hi,

I am new here. I am getting this error while viewing any of my WordPress page or post “

Fatal error: Uncaught TypeError: call_user_func_array(): Argument #1 ($callback) must be a valid callback, no array or string given in E:\xampp\htdocs\wordpress\wp-includes\class-wp-hook.php:308 Stack trace: #0 E:\xampp\htdocs\wordpress\wp-includes\class-wp-hook.php(332): WP_Hook->apply_filters(NULL, Array) #1 E:\xampp\htdocs\wordpress\wp-includes\plugin.php(517): WP_Hook->do_action(Array) #2 E:\xampp\htdocs\wordpress\wp-includes\general-template.php(3049): do_action(‘wp_head’) #3 E:\xampp\htdocs\wordpress\wp-includes\template-canvas.php(17): wp_head() #4 E:\xampp\htdocs\wordpress\wp-includes\template-loader.php(106): include(‘E:\xampp\htdocs…’) #5 E:\xampp\htdocs\wordpress\wp-blog-header.php(19): require_once(‘E:\xampp\htdocs…’) #6 E:\xampp\htdocs\wordpress\index.php(17): require(‘E:\xampp\htdocs…’) #7 {main} thrown in E:\xampp\htdocs\wordpress\wp-includes\class-wp-hook.php on line 308

I was basically making a plugin. The plugin works fine in live server or website. But in localhost, I am getting that fatal error and am unable to view any post or page. I am unable to debug or catch the problem because I don’t know which callback function and argument I need to update? May I get solution about what callback function and argument I need to update?

Doubt

What's the issue with making it to production?

Issues with creating the instance for the migration class.

function applyMigrations() {
    $this->createMigrationsTable();
    $appliedMigrations = $this->getAppliedMigrations();

    $newMigrations = [];
    $files = scandir(Application::$ROOT_DIR . '/migrations');
    $toApplyMigrations = array_diff($files, $appliedMigrations);

    foreach ($toApplyMigrations as $migration) {
      if ($migration === '.' || $migration === '..') {
        continue;
      }

      require_once Application::$ROOT_DIR .'./migrations/'.$migration;
      $className = pathinfo($migration, PATHINFO_FILENAME);

      echo "<pre>";
      var_dump($className);
      echo "</pre>";
      exit;

      $instance = new $className();      //ISSUE CREATING THIS INSTANCE!!
      $this->log("Applying migration $migration");
      $instance->up();
      $this->log("Applied migration $migration");
      $newMigrations[] = $migration;
      echo "<pre>";
      var_dump($instance);
      echo "</pre>";
      exit;
    }
  }

Hi thecodeholic, i am having this error creating the instance for the migration class:

Fatal error: Uncaught Error: Class "m0001_initial" not found in C:\xampp\htdocs\simpleMVC\core\Database.php

would really appreciate if you could help me.

I really do appreciate your PHP tutorials, it makes me really enjoy coding PHP!

Couldn`t figure out how to link to a local files/libraries (images, css, js)

Hello there,

thanks a lot for the the great course and the lovely educational materials. Im learning an experimenting with the framework and couldnt figure out how to modify the code to link to local js, css files instead of the online ones (JQuery, Bootstrap ..etc).

I tried all the tricks I know, with no avail. could you please help with that?

How to render js files in views

Hello thecodeholic ,
thanks a lot for the the great course and the lovely educational materials . in layouts/main.php there exist {{content}} and as i understood it's to replace the content of view , how can i make similar to this but for js files , i want to load js file in my view without putting it in layouts/main.php beofr tag

Solution to " Uncaught TypeError: call_user_func(): Argument #1 ($callback) must be a valid callback, non-static method app\controllers\SiteController::contact() cannot be called statically" error during the implementation of the controller

hello, i'm using php 8.x, i solved this problem making static every function in SiteController (where i had to use SiteController), based on the documentation in the version 8.x the operator :: is used for static functions, i also had to use use app\core\Application in the SiteController to include Application in SiteController. I write down this here just in the case other one had the same problem. (sorry for my english, I'm not a native speaker)

After device restart, Completed Application cant find requested resource / on this server at localhost:8080

After completing the application and getting it to work properly, I saved my progress and exited PHP Storm.

I returned to stylize and add some additional features, but upon trying to run the app on localhost:8080 through the PHP storm's built-in server I get the following error:

Screenshot 2022-04-17 221043

However, I can not navigate to 127.0.0.1 to see my root directory now. It just defaults to the XAMPP dashboard, and similarly, 127.0.0.1:8080 refuses to connect ... Does anyone have a hunch about why this is happening?

localhost:8080 is returning a favicon with a 200 status code, from my Application's directory, but it's failing to route '/' to the home page. My hunch was that it is a composer or autoload related and I'm being very amateur and missing some configuration or initiation process upon restarting my computer and PHP Storm.

Here's my composer.json config:
Screenshot 2022-04-18 000504

Still at a loss as to how to get this up and running correctly. Any help would be appreciated, as this has been a cool project to work on, and I want to understand my error here.

Cannot Find Core Folder

Hello @thecodeholic I have been following your tutorial. But I cannot find the core folder within this repo. Can you please share with us where the folder is? As it is very important all the main classes are there.

Also I want to keep track of the changes you have made after each video.

Thank you .

I can't make it work on Xampp server

Hey, I'm using XAMPP server and I have simple htaccess to redirect to public folder. My router is not working correctly. If the uri is "/" it's working but when I type uri localhost/contact doesn't show the message or error and doesn't load. I got error from xampp server page not found. Even with out the htaccess file doesn't work. I also created virtual host but without results

Listen 81
<VirtualHost *:81>
DocumentRoot "F:\mvc\public"
<Directory "F:\mvc\public">
AllowOverride All
Require all granted

htaccess:

RewriteEngine On
RewriteBase /

RewriteCond %{THE_REQUEST} /public/([^\s?]*) [NC]
RewriteRule ^ %1 [L,NE,R=302]

RewriteRule ^((?!public/).*)$ public/$1 [L,NC]

Integrity constraint violation: 1052 Column 'id'

I tried to adjust your code to allow for a bespoke sql with INNER JOIN.
However there is an issue with integrity constraint on where.

How would we get over integrity constraints using your bind method i.e :

Employee (e)
id   name   started 
1    John    2010-01-02

Sales (s)
id     month   employee_id   income   volume
34       1        1           50000     1500

MODEL

public static function findSales($where){

      $sql="SELECT e.id, e.name,s.volume,s.income  FROM employee as e INNER JOIN sales as s ON e.id=s.employee_id";
      
      $attributes=array_keys($where);
      
      $add_sql=implode(" AND ", array_map(fn ($attr) => "$attr=:$attr",$attributes));
      $statement=self::prepare("$sql WHERE $add_sql");
      foreach ($where as $key => $value) {
	   $statement->bindValue(":$key",$value);
      }
      $statement->execute();
      return $statement->fetchObject(static::class);
}

CONTROLLER**

$sale=Employee::findSales(['month'=>1,'id'=>1]);

As we cannot use findSales(['month'=>1,'e.id'=>1])
Is there a way to adjust your attribute function to specify the id for the where clause to avoid ambiguity on the id ?

Gives: Deprecated: Non-static method


Deprecated: Non-static method app\models\User::primaryKey() should not be called statically in /Applications/XAMPP/xamppfiles/htdocs/php/mvc/core/Application.php on line 34

Deprecated: Non-static method app\core\DbModel::findOne() should not be called statically in /Applications/XAMPP/xamppfiles/htdocs/php/mvc/core/Application.php on line 35

Deprecated: Non-static method app\models\User::tableName() should not be called statically in /Applications/XAMPP/xamppfiles/htdocs/php/mvc/core/DbModel.php on line 34

Commit where you have created .findOne() function
e9e01dd

Restricting url from parameter use with ?

Hi,
Just wondered if on the index page you can set the router to not allow any ? parameters and allow ?query=xxx but restrict what parameters are allowable.

e.g.
$app->router->get('/test', [SiteController::class, 'test']);

mysite.com/test?dddd is currently accessible for any test?xxxxx

Can we restrict it to:
mysite.com/test

Another page I would like it to read:
mysite.com/blog?p=1
specifying only p as a query parameter.

How to avoid repeated code in each controller?

@thecodeholic. Thank you once again for this great contribution. Your tutorials are excellent. I would like to have an idea on the following:
The constructor of the AuthController class is responsible for registering each of the middleware. If I had 10 more controllers, and I didn't want to repeat the code in each constructor. What should I do?

  1. Create a trait to register the middleware and use it only in the necessary controllers?
  2. Move middleware registration to Core's Controller class constructor?... all controllers will be affected :-(
  3. Replicate the AuthController class constructor code.

Have a nice day @thecodeholic

call_user_func() expects non-static method

Why is that? Is it part of the last PHP 7.4 updates?

Setting public static funcion won't cause any future problems?

Also, it is curious that the error is pointed, but the return of the function still appears below it.

Screenshot_2021-02-23 Screenshot

Isn't it better to instatiate SiteController, then call for it?

As follows:

$siteController = new SiteController();
$app->router->get('/contact', [$siteController, 'contact']);

HOW TO INTEGRATE AJAX?

I had fun integrating ajax and it works great. How would you do it?

1. I added to index.php:

$ app-> router-> post ('/ ajax', [AuthController :: class, 'ajaxMethod']);

2. In the AuthController.php

public function ajaxMethod (Request $ request) {
echo $ result;
}

3. In the view: register.php (... or any view, with some request)

   $ .ajax ({
       method: "POST",
       url: '/ ajax',
       data: { ... }
   })
   .done (function (result) {
         console.log (result);
   });

NOTE: Works great.
I am sending from the view the url: '/ ajax'. The router.php recognizes it, sends it to AuthController.php, executes the ajaxMethod () and responds without reloading the page. You will see the result on the console.

  • Any other input or observation?

  • Is there another alternative to ajax and not reloading the page in a request?

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.