Quick Start

Last updated: 3 days ago

Download

Get started with ZenithPHP, a lightweight and flexible PHP framework designed for ease of use and rapid development. Ideal for developers seeking simplicity and efficiency, ZenithPHP offers a clean, intuitive structure for building MVC applications. Learn more about the framework to explore its core features and components.

Download ZenithPHP

Installation

Step One: Clone the Repository

To get started with ZenithPHP, clone the framework repository from GitHub to your local environment.

Command:

git clone https://github.com/ZenithPHP-Framework/full-zenith-framework.git

Step Two: Navigate to the Directory and Install Dependencies

Once cloned, navigate to the project folder and install the necessary dependencies using Composer.

Commands:

cd full-zenith-framework

composer install

Step Three: Configure Environment Variables

Copy the example environment file to set up your environment variables. Configure database credentials and other necessary settings.

Command:

cp .env.example .env

Open the .env file and update it with your specific configuration values.

Step Four: Start the Development Server

To run the application locally, start the built-in development server using the command below.

Command:

php cli run

Visit http://localhost:8000 in your browser to view the landing page.

Code

Creating Controllers

To create a controller in ZenithPHP, use the following command:

CLI Command
php cli make:controller WelcomeController

This command will create a new file named WelcomeController.php in the App/Controllers directory. You can define your controller’s actions here.

Example Code
<?php
namespace App\Controllers;

use ZenithPHP\Core\Controller\Controller;
use ZenithPHP\Core\Http\Request;
use ZenithPHP\Core\Http\Response;

class WelcomeController extends Controller
{
    public function index(Request $request, Response $response)
    {
        // Load a view file
        $this->view('welcome');
    }
}
?>

Configuring Controllers

In the App/routes.php file, configure routes for your controller methods.

Route Example
use ZenithPHP\Core\Http\Router;

// Define a route to your controller’s action
Router::get('/welcome', 'WelcomeController', 'index');

Creating Models

To create a new model, use the command below:

CLI Command
php cli make:model User

This command generates a User.php file in the App/Models directory. Define the model's properties and relationships within this file.

Example Code
<?php
namespace App\Models;

use ZenithPHP\Core\Database\Model;

class User extends Model
{
    protected $table = 'users';
}
?>

Creating Migrations

To set up database tables, you can create migrations. Use the command:

CLI Command
php cli make:migration users

Save your migration files in the Migrations folder. Each migration should extend the Migration class.

Example Migration
<?php
use ZenithPHP\Core\Database\Migration;
use ZenithPHP\Core\Database\Schema;

class _2024_10_27_174853_users extends Migration
{
    public function up()
    {
        Schema::create('users', function (Schema $table) {
            $table->id();
            $table->string('name');
            $table->string('email');
            $table->timestamps();
        });
    }

    public function down()
    {
        Schema::dropIfExists('users');
    }
}
?>

Advanced

Working with APIs | Added in v2.0

ZenithPHP makes it easy to create APIs for your application. Follow these steps to create a simple API that retrieves user data.

Step 1: Define the API Route

Start by creating a new route in the App/routes.php file. This route will map the API endpoint to a specific controller action.

Example Route Definition

use ZenithPHP\Core\Http\Router;
Router::get('/api/users', 'UserController', 'index');
    

Step 2: Create a User Model

Use the CLI tool to create a new model for your API. This model will handle data interaction with the database.

Create a Model

php cli make:model User
    

In the generated User model, define the database table name to interact with. Here’s an example:

Define the User Model

use ZenithPHP\Core\Model\Model;

class User extends Model
{
    protected string $table_name = 'users';
}
    

Step 3: Create a User Controller

Next, create a controller that will fetch data from the User model and return it as JSON. Use the CLI tool to generate this controller.

Create a Controller

php cli make:controller UserController
    

Step 4: Implement the Controller Method

In the UserController, define the index method to handle incoming requests, fetch data from the User model, and return it as a JSON response.

Controller Implementation

use ZenithPHP\Core\Controller\Controller;
use ZenithPHP\Core\Http\Response;
use ZenithPHP\Core\Http\Request;
use ZenithPHP\App\Models\User;

class UserController extends Controller
{
    public function index(Request $request, Response $response)
    {
        $user = new User($this->pdo);
        $allUsers = $user->getAll();
        $response->json(['status' => 'success', 'data' => $allUsers]);
    }
}
    

Step 5: Access the API

Once everything is set up, you can access the API by visiting http://localhost:8000/api/users in your browser. This should return a JSON response with user data.

Sample JSON Response

{
    "status": "success",
    "data": [
        {
            "id": 1,
            "name": "John Doe",
            "email": "johndoe@example.com"
        },
        {
            "id": 2,
            "name": "Jane Smith",
            "email": "janesmith@example.com"
        }
    ]
}
    

This simple example demonstrates how you can set up an API in ZenithPHP to serve JSON data. You can create additional routes and methods to handle other data interactions and enhance your API functionality.

Using Middleware | Added in v2.0

Middleware in ZenithPHP enables you to apply logic before or after a request is processed. This functionality is helpful for enforcing access controls, logging requests, or modifying requests and responses.

For instance, the AuthMiddleware can restrict access based on authentication or specific user roles. You can define middleware classes to manage various tasks, such as ensuring that users are authenticated or have a specific role before accessing certain routes.

Creating Middleware

To create a middleware, define a class in the App\Middleware namespace and extend the base Middleware class. Middleware classes contain a handle method that checks the request and response, performs any necessary logic, and optionally calls the $next function to continue processing the request.

Example: AuthMiddleware

namespace ZenithPHP\App\Middleware;

use ZenithPHP\Core\Http\Request;
use ZenithPHP\Core\Http\Response;
use ZenithPHP\Core\Middleware\Middleware;

class AuthMiddleware extends Middleware
{
    protected string $role;

    public function __construct(string $role = '')
    {
        $this->role = $role;
    }

    public function handle(Request $request, Response $response, callable $next)
    {
        session_start();
        $user = $_SESSION['user'] ?? null;

        if ($this->role && (!$user || $user['role'] !== $this->role)) {
            $response->send("Unauthorized", 403);
            exit();
        }

        if (!$user && $this->role === '') {
            $response->send("Please login", 401);
            exit();
        }

        // Call the next middleware or controller action
        return $next($request, $response);
    }
}
    

Using Middleware in Routes

Once you've defined a middleware class, you can apply it to routes to enforce specific access rules. In the example below, the auth middleware restricts access to authenticated users, while auth:admin restricts it to users with an "admin" role.

Example Usage

Router::get('/dashboard', 'DashboardController', 'index')->only('auth');
Router::get('/admin', 'AdminController', 'index')->only('auth:admin');
    

These routes will only be accessible to users who meet the specified middleware requirements, ensuring secure access control and reducing the risk of unauthorized access.

Introduction to Pluto Template Engine | Added in v2.0

The Pluto template engine in ZenithPHP allows you to easily build dynamic views with clean and readable syntax. It’s designed to simplify templating and enhance the readability of your views, using special tags for logic and variables.

Pluto Syntax

Pluto introduces a set of custom tags and directives that allow you to insert dynamic data, control the flow, and loop through data collections. Here’s a quick overview:

  • Variable Output: Use << $variable >> to output PHP variables in the view.
  • Conditional Statements: Pluto offers @if, @elseif, @else, and @endif directives for conditional rendering.
  • Looping: Use @foreach and @endforeach to iterate over collections.
  • PHP Code: Use @php and @endphp to include raw PHP code.
  • Sections and Yields: Use @section and @yield for layout management.
  • Comments: Use << // comment text >> for comments.

Pluto Engine Tags

Example Syntax

<!-- Displaying a variable -->
<< $username >>

<!-- Conditional Statement -->
@if ($userRole == 'admin')
  <p>Welcome, Admin!</p>
@elseif ($userRole == 'member')
  <p>Welcome, Member!</p>
@else
  <p>Welcome, Guest!</p>
@endif

<!-- Looping Through Data -->
@foreach ($items as $item)
  <p><< $item->name >> - << $item->price >></p>
@endforeach

<!-- Using PHP Code -->
@php
  $count = count($items);
@endphp

Total items: << $count >>

<!-- Defining Sections and Yields --> @section('content') <p>This is the main content area.</p> @endsection @yield('content') <!-- Where the content will be injected --> <!-- Pluto Comment --> << // This is a comment that won't be rendered >>

Getting Started with Pluto

To create a new view using the Pluto template engine, follow these steps:

  1. Navigate to the View folder in the root directory of your ZenithPHP project.
  2. Create a new file and name it home.pluto.php (you can replace home with your desired filename).
  3. In the newly created file, you can start using the Pluto syntax to build your view.

Using Pluto Engine in Views

To render a view using Pluto, specify the path to the template file. The engine will automatically parse the Pluto syntax and render the final HTML.

Example Usage

class HomeController extends Controller 
{
    public function index(Request $request, Response $response)
    {
        return view('home', [
            'username' => 'John Doe',
            'userRole' => 'admin',
            'items' => [
                (object) ['name' => 'Laptop', 'price' => '$999'],
                (object) ['name' => 'Smartphone', 'price' => '$499'],
            ]
        ]);
    }
}
        

Benefits of Using Pluto

With Pluto, you can keep logic out of your views, making them cleaner and more maintainable. It provides a straightforward syntax for working with dynamic data and helps developers create well-structured and easily understandable templates.