PHPackages                             stanislasdevfr/phpmvc - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. [Framework](/categories/framework)
4. /
5. stanislasdevfr/phpmvc

ActiveLibrary[Framework](/categories/framework)

stanislasdevfr/phpmvc
=====================

A lightweight PHP MVC project generator with Bootstrap and authentication

v1.0.0(8mo ago)16MITPHPPHP &gt;=8.0

Since Oct 17Pushed 8mo agoCompare

[ Source](https://github.com/stanislasdevfr/phpmvc)[ Packagist](https://packagist.org/packages/stanislasdevfr/phpmvc)[ Docs](https://github.com/stanislasdevfr/phpmvc)[ RSS](/packages/stanislasdevfr-phpmvc/feed)WikiDiscussions main Synced today

READMEChangelog (1)Dependencies (1)Versions (2)Used By (0)

PhpMvc Generator
================

[](#phpmvc-generator)

 [![PHP Version](https://camo.githubusercontent.com/2f6f9af2e917cbf5786673e8e4ed8d0d9b29be6131327a992063e69136a93411/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f5048502d382e302532422d626c7565)](https://camo.githubusercontent.com/2f6f9af2e917cbf5786673e8e4ed8d0d9b29be6131327a992063e69136a93411/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f5048502d382e302532422d626c7565) [![License](https://camo.githubusercontent.com/5caa455d8debc46fb23abbadb45a733a937f3910a73fc875c2f7820468e1bb54/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f4c6963656e73652d4d49542d677265656e)](https://camo.githubusercontent.com/5caa455d8debc46fb23abbadb45a733a937f3910a73fc875c2f7820468e1bb54/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f4c6963656e73652d4d49542d677265656e) [![Status](https://camo.githubusercontent.com/7ad747e5eefa3aa1040130a413dd5d018f22edbc45638ea213a3376a278e76f6/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f5374617475732d537461626c652d73756363657373)](https://camo.githubusercontent.com/7ad747e5eefa3aa1040130a413dd5d018f22edbc45638ea213a3376a278e76f6/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f5374617475732d537461626c652d73756363657373)

A lightweight and powerful PHP MVC project generator that creates a complete, production-ready application with entities, repositories, controllers, and optional Bootstrap views and authentication system.

✨ Features
----------

[](#-features)

- **🚀 Rapid Development**: Generate a complete MVC structure in seconds
- **🎨 Bootstrap 5 Integration**: Optional responsive UI with modals and AJAX
- **🔐 Authentication System**: Complete login/register system with password hashing
- **🗄️ Repository Pattern**: Clean separation between business logic and data access
- **💉 Auto-Hydration**: Automatic entity hydration from arrays
- **🛣️ Smart Router**: RESTful routing with automatic CRUD routes
- **🔒 Security First**: Prepared statements, password hashing, input validation
- **📱 Hybrid Controllers**: Support both API (JSON) and HTML views
- **⚡ AJAX Ready**: Modern SPA-like experience with Bootstrap modals
- **🎯 PSR-4 Autoloading**: Modern PHP standards
- **🌐 i18n Ready**: All generated code in English

📋 Requirements
--------------

[](#-requirements)

- **PHP** 8.0 or higher
- **Composer** (dependency manager)
- **MySQL** or **MariaDB** database
- Web server (Apache, Nginx) or PHP built-in server

📦 Installation
--------------

[](#-installation)

Install the generator globally via Composer:

```
composer global require phpmvc/phpmvc
```

Or install it in a specific project:

```
composer require phpmvc/phpmvc --dev
```

🚀 Quick Start
-------------

[](#-quick-start)

### 1. Generate a new project

[](#1-generate-a-new-project)

```
php vendor/bin/phpmvc init
```

Or if installed globally:

```
phpmvc init
```

### 2. Answer the interactive questions

[](#2-answer-the-interactive-questions)

```
📁 Project name: my-blog
🔢 Number of entities: 2

━━━ Entity #1 ━━━
📝 Entity #1 name: Post
➜ Field name: title
➜ Type (string/int/float/bool/datetime): string
➜ Field name: content
➜ Type: text
➜ Field name: (leave empty to finish)

━━━ Entity #2 ━━━
📝 Entity #2 name: Category
➜ Field name: name
➜ Type: string
➜ Field name: (leave empty)

🎨 Generate Bootstrap views? (y/n): y
🔐 Generate authentication system? (y/n): y

```

### 3. ⚠️ **IMPORTANT - Database Setup**

[](#3-️-important---database-setup)

**Before running your project, you MUST create your MySQL database:**

```
CREATE DATABASE my_blog CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;
```

If you enabled authentication, also create the users table:

```
CREATE TABLE users (
    id INT AUTO_INCREMENT PRIMARY KEY,
    email VARCHAR(255) NOT NULL UNIQUE,
    password VARCHAR(255) NOT NULL,
    name VARCHAR(255) NOT NULL,
    created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP
);
```

Create tables for your entities:

```
CREATE TABLE posts (
    id INT AUTO_INCREMENT PRIMARY KEY,
    title VARCHAR(255) NOT NULL,
    content TEXT NOT NULL
);

CREATE TABLE categories (
    id INT AUTO_INCREMENT PRIMARY KEY,
    name VARCHAR(255) NOT NULL
);
```

### 4. Configure database connection

[](#4-configure-database-connection)

Edit `config/database.php`:

```
return [
    'host' => 'localhost',
    'database' => 'my_blog',        // ← Your database name
    'username' => 'root',           // ← Your MySQL username
    'password' => '',               // ← Your MySQL password
    'charset' => 'utf8mb4',
    'options' => [
        PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
        PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
        PDO::ATTR_EMULATE_PREPARES => false,
    ]
];
```

### 5. Install dependencies and run

[](#5-install-dependencies-and-run)

```
cd my-blog
composer install
php -S localhost:8000 -t public
```

### 6. Access your application

[](#6-access-your-application)

Open your browser:

- **Home**:
- **Login**:
- **Register**:

📁 Generated Project Structure
-----------------------------

[](#-generated-project-structure)

```
my-blog/
├── public/
│   └── index.php              # Application entry point
├── src/
│   ├── Entity/                # Your entities (Post, Category, User)
│   ├── Repository/            # Database access layer
│   ├── Controller/            # Business logic (CRUD operations)
│   ├── View/                  # Bootstrap views (if enabled)
│   └── Core/                  # Core classes
│       ├── Database.php       # PDO connection (singleton)
│       ├── Hydrator.php       # Entity hydration
│       ├── Router.php         # URL routing
│       ├── Session.php        # Session management (if auth enabled)
│       └── AuthMiddleware.php # Route protection (if auth enabled)
├── config/
│   ├── database.php           # Database configuration
│   └── routes.php             # Route definitions
├── vendor/                    # Composer dependencies
├── composer.json              # Project dependencies
├── .gitignore                 # Git ignore rules
└── README.md                  # Project documentation

```

🎯 What Gets Generated
---------------------

[](#-what-gets-generated)

### For each entity (e.g., `Post`):

[](#for-each-entity-eg-post)

#### 1. **Entity** (`src/Entity/Post.php`)

[](#1-entity-srcentitypostphp)

```
- Private properties with type hints
- Constructor
- hydrate() method for automatic population
- Getters and setters for all fields
```

#### 2. **Repository** (`src/Repository/PostRepository.php`)

[](#2-repository-srcrepositorypostrepositoryphp)

```
- findAll(): array          // Get all records
- findById(int $id): ?Post  // Get by ID
- save(Post $post): void    // Create or update
- delete(int $id): void     // Delete record
```

#### 3. **Controller** (`src/Controller/PostController.php`)

[](#3-controller-srccontrollerpostcontrollerphp)

```
- index()           // List all (public access)
- show($id)         // Show one (public access)
- create()          // Show form (public access)
- store()           // Create (requires auth if enabled)
- edit($id)         // Get data for edit (public access)
- update($id)       // Update (requires auth if enabled)
- delete($id)       // Delete (requires auth if enabled)
```

#### 4. **View** (`src/View/post_index.php`) - If Bootstrap enabled

[](#4-view-srcviewpost_indexphp---if-bootstrap-enabled)

```
- Responsive table with data
- Create/Edit/View/Delete modals
- AJAX operations (no page reload)
- Real-time alerts
```

#### 5. **Routes** (`config/routes.php`)

[](#5-routes-configroutesphp)

```
GET    /posts           → PostController::index()
GET    /posts/{id}      → PostController::show($id)
GET    /posts/create    → PostController::create()
POST   /posts           → PostController::store()
GET    /posts/{id}/edit → PostController::edit($id)
POST   /posts/{id}      → PostController::update($id) [_method=PUT]
POST   /posts/{id}      → PostController::delete($id) [_method=DELETE]
```

🔐 Authentication System (if enabled)
------------------------------------

[](#-authentication-system-if-enabled)

### Features

[](#features)

- **User Registration** with validation
- **Login/Logout** with session management
- **Password Hashing** using bcrypt
- **Route Protection** for write operations
- **Session Management** with helper class

### Authentication Routes

[](#authentication-routes)

```
GET/POST /login         // Login page and process
GET/POST /register      // Registration page and process
GET      /logout        // Logout and destroy session
GET      /auth/check    // Check auth status (API)
```

### Protected Routes

[](#protected-routes)

When authentication is enabled:

- ✅ **Public access**: `index()`, `show()`, `create()`, `edit()`
- 🔒 **Requires login**: `store()`, `update()`, `delete()`

### Using Authentication in Your Code

[](#using-authentication-in-your-code)

```
// In a controller
use App\Core\Session;
use App\Core\AuthMiddleware;

// Check if user is authenticated
if (Session::isAuthenticated()) {
    $userId = Session::getUserId();
    $user = Session::get('user');
}

// Protect a route manually
AuthMiddleware::requireAuth();

// Require guest (not logged in)
AuthMiddleware::requireGuest();
```

🌐 API Usage
-----------

[](#-api-usage)

All controllers support JSON responses for API usage:

### List all posts

[](#list-all-posts)

```
curl http://localhost:8000/posts \
  -H "X-Requested-With: XMLHttpRequest"
```

Response:

```
[
    {"id": 1, "title": "First Post", "content": "..."},
    {"id": 2, "title": "Second Post", "content": "..."}
]
```

### Create a post

[](#create-a-post)

```
curl -X POST http://localhost:8000/posts \
  -d "title=New Post&content=Great content"
```

Response:

```
{
    "success": true,
    "id": 3,
    "message": "Post created successfully"
}
```

### Update a post

[](#update-a-post)

```
curl -X POST http://localhost:8000/posts/3 \
  -d "_method=PUT&title=Updated&content=New content"
```

### Delete a post

[](#delete-a-post)

```
curl -X POST http://localhost:8000/posts/3 \
  -d "_method=DELETE"
```

🎨 Bootstrap Views
-----------------

[](#-bootstrap-views)

When Bootstrap is enabled, you get:

- **Responsive Layout** with navbar and footer
- **Modal-based CRUD** (no page reloads)
- **AJAX Operations** with real-time updates
- **Bootstrap Icons** for actions
- **Alert System** for feedback
- **Form Validation** with visual feedback

### View Structure

[](#view-structure)

Each entity gets:

```
{entity}_index.php
├── List table with data
├── Create modal
├── Edit modal
├── View modal
└── Delete confirmation modal
```

🔧 Customization
---------------

[](#-customization)

### Adding Custom Routes

[](#adding-custom-routes)

Edit `config/routes.php`:

```
// Custom route
$router->get('/about', 'PageController', 'about');
$router->post('/contact', 'ContactController', 'send');

// Protect a specific route
// In your controller:
\App\Core\AuthMiddleware::requireAuth();
```

### Adding New Fields to Entity

[](#adding-new-fields-to-entity)

1. Add the field to your database table
2. Add property, getter, and setter to entity
3. Update repository if needed
4. Add field to view forms

### Modifying Views

[](#modifying-views)

Views are in `src/View/`. Edit them directly:

- Modify HTML structure
- Change Bootstrap classes
- Add custom JavaScript
- Customize forms

🐛 Troubleshooting
-----------------

[](#-troubleshooting)

### Error: "Connection error"

[](#error-connection-error)

**Problem**: Cannot connect to MySQL database

**Solutions**:

1. Verify MySQL is running: `mysql --version`
2. Check credentials in `config/database.php`
3. Ensure database exists: `CREATE DATABASE your_db_name;`
4. Check MySQL port (default: 3306)

### Error: "Class not found"

[](#error-class-not-found)

**Problem**: Autoloading issue

**Solution**: Run `composer dump-autoload`

### Error: "Route not found"

[](#error-route-not-found)

**Problem**: Routes not configured correctly

**Solutions**:

1. Check `config/routes.php` exists
2. Verify router is loaded in `public/index.php`
3. Clear browser cache

### Error: "Call to undefined method"

[](#error-call-to-undefined-method)

**Problem**: Missing method in controller/repository

**Solution**: Regenerate the entity/controller or add method manually

### Bootstrap views not working

[](#bootstrap-views-not-working)

**Problem**: AJAX requests failing

**Solutions**:

1. Check browser console for JavaScript errors
2. Verify routes are correct in `config/routes.php`
3. Ensure CDN links are accessible (check internet connection)

### Authentication not working

[](#authentication-not-working)

**Problem**: Login/register not functioning

**Solutions**:

1. Verify `users` table exists in database
2. Check Session class is loaded
3. Clear browser cookies/session
4. Verify `AuthMiddleware.php` exists in `src/Core/`

🔒 Security Features
-------------------

[](#-security-features)

PhpMvc Generator includes several security features:

- ✅ **Prepared Statements**: All SQL queries use PDO prepared statements (prevents SQL injection)
- ✅ **Password Hashing**: Bcrypt hashing for passwords (no plain text storage)
- ✅ **Input Validation**: Automatic validation based on field types
- ✅ **Type Safety**: PHP 8 type hints throughout
- ✅ **Session Security**: Secure session management
- ✅ **CSRF Protection**: Ready for CSRF token implementation
- ✅ **XSS Prevention**: Use `htmlspecialchars()` in views for user input

### Additional Security Recommendations

[](#additional-security-recommendations)

1. **In Production**:

    - Change default database credentials
    - Use HTTPS
    - Set secure session cookies
    - Enable error logging (disable display)
    - Keep dependencies updated
2. **Add CSRF Protection**:

```
// In forms:
