PHP code example of machinjiri / framework

1. Go to this page and download the library: Download machinjiri/framework library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

machinjiri / framework example snippets


// routes/web.php
use Mlangeni\Machinjiri\Core\Routing\Router;

Router::get('/', function() {
    return 'Welcome to Machinjiri!';
});

Router::get('/hello/{name}', function($name) {
    return "Hello, {$name}!";
}, 'greeting');

// app/Controllers/HomeController.php
namespace Mlangeni\Machinjiri\App\Controllers;

class HomeController
{
    public function index()
    {
        return view('home', ['title' => 'Home Page']);
    }
}

// routes/web.php
Router::get('/', 'HomeController@index', 'home');

use Mlangeni\Machinjiri\Core\Routing\Router;

// Simple routes
Router::get('/users', 'UserController@list');
Router::post('/users', 'UserController@store');
Router::put('/users/{id}', 'UserController@update');
Router::delete('/users/{id}', 'UserController@destroy');
Router::patch('/users/{id}', 'UserController@patch');
Router::any('/path', 'Controller@method');

// Named routes
Router::get('/profile/{id}', 'UserController@show', 'user.profile');

// Route groups
Router::group(['prefix' => '/api', 'middleware' => 'api'], function() {
    Router::get('/users', 'ApiUserController@list');
    Router::post('/users', 'ApiUserController@store');
});

// AJAX routes
Router::ajax('/api/data', 'ApiController@getData');

// Traditional routes
Router::traditional('/contact', 'ContactController@show');

// Generate URLs
$url = Router::route('user.profile', ['id' => 5]);
$absoluteUrl = Router::absoluteRoute('user.profile', ['id' => 5]);

// Apply middleware to routes
Router::group(['middleware' => 'auth'], function() {
    Router::get('/dashboard', 'DashboardController@index');
});

// Multiple middleware
Router::group(['middleware' => ['auth', 'admin']], function() {
    Router::get('/admin', 'AdminController@dashboard');
});

// Middleware with parameters
Router::group(['middleware' => 'role:admin'], function() {
    Router::delete('/users/{id}', 'UserController@destroy');
});

Router::cors([
    'allowed_origins' => ['https://example.com'],
    'allowed_methods' => ['GET', 'POST', 'OPTIONS'],
    'allowed_headers' => ['Content-Type', 'Authorization'],
], function() {
    Router::get('/api/public', 'ApiController@public');
});

<% if $user->isAdmin() %>
    <a href="/admin">Admin Panel</a>
<% else %>
    <a href="/profile">My Profile</a>
<% endif %>

<% foreach $products as $product %>
    <div>{{ $product->name }} - {{ $product->price }}</div>
<% endforeach %>

use Mlangeni\Machinjiri\Core\Views\View;

public function index($req, $res)
{
    return View::make('home', [
        'title' => 'Home Page',
        'featured' => $featured,
    ])->render();
    
    // Or display directly
    View::make('home', ['title' => 'Home'])->display();
    
    // Share data globally
    View::share('user', auth()->user());
}

// config/database.php
return [
    'driver' => env('DB_CONNECTION', 'mysql'),
    'host' => env('DB_HOST', 'localhost'),
    'username' => env('DB_USERNAME', 'root'),
    'password' => env('DB_PASSWORD', ''),
    'database' => env('DB_DATABASE', 'machinjiri'),
    'port' => env('DB_PORT', 3306),
];

use Mlangeni\Machinjiri\Core\Database\QueryBuilder;

// Simple queries
$users = QueryBuilder::table('users')->get();
$user = QueryBuilder::table('users')->where('id', 5)->first();

// Complex queries
$result = QueryBuilder::table('users')
    ->select(['id', 'name', 'email'])
    ->where('active', true)
    ->where('role', 'admin')
    ->orderBy('name', 'asc')
    ->limit(10)
    ->get();

// Insert
QueryBuilder::table('users')->insert([
    'name' => 'John',
    'email' => '[email protected]',
]);

// Update
QueryBuilder::table('users')
    ->where('id', 5)
    ->update(['name' => 'Jane']);

// Delete
QueryBuilder::table('users')->where('id', 5)->delete();

// Aggregate functions
$count = QueryBuilder::table('users')->count();
$max = QueryBuilder::table('posts')->max('views');

// database/migrations/2024_01_01_000000_create_users_table.php
class CreateUsersTable
{
    public function up()
    {
        Schema::create('users', function($table) {
            $table->increments('id');
            $table->string('name');
            $table->string('email')->unique();
            $table->string('password');
            $table->timestamps();
        });
    }
    
    public function down()
    {
        Schema::dropIfExists('users');
    }
}

// config/auth.php
return [
    'guard' => 'web',
    'providers' => [
        'users' => [
            'driver' => 'database',
            'table' => 'users',
        ],
    ],
];

// In your controller
public function login($req, $res)
{
    $credentials = $req->only(['email', 'password']);
    
    if (auth()->attempt($credentials)) {
        return $res->redirect('/dashboard');
    }
    
    return view('auth.login', ['error' => 'Invalid credentials']);
}

public function logout($req, $res)
{
    auth()->logout();
    return $res->redirect('/');
}

use Mlangeni\Machinjiri\Core\Authentication\OAuth;

$oauth = new OAuth($config);
$token = $oauth->getAccessToken($code);
$user = $oauth->getUserInfo($token);

use Mlangeni\Machinjiri\Core\Forms\Password;

// Hash password
$hashed = Password::hash('secret123');

// Verify password
if (Password::verify('secret123', $hashed)) {
    // Password is correct
}

// Automatically handled in forms
<form method="POST" action="/users">
    <input type="hidden" name="_token" value="<%= csrf_token() %>">
    <!-- form fields -->
</form>

use Mlangeni\Machinjiri\Core\Security\Encryption\Cipher;

$encrypter = new Cipher($key);
$encrypted = $encrypter->encrypt($data);
$decrypted = $encrypter->decrypt($encrypted);

use Mlangeni\Machinjiri\Core\Forms\FormValidator;

public function store($req, $res)
{
    $validator = new FormValidator($req->all());
    
    $validator->validate([
        'name' => '=> $validator->errors()]);
    }
    
    // Create user
    User::create($validator->validated());
}

$validator = new FormValidator($data);

$validator->validate([
    'age' => [
        'e < 18) {
                $fail('Must be 18 or older');
            }
        },
    ],
]);

// app/Jobs/SendWelcomeEmail.php
namespace Mlangeni\Machinjiri\App\Jobs;

use Mlangeni\Machinjiri\Core\Artisans\Contracts\JobInterface;

class SendWelcomeEmail implements JobInterface
{
    public $data;
    
    public function __construct($userId)
    {
        $this->data = ['user_id' => $userId];
    }
    
    public function handle()
    {
        $user = User::find($this->data['user_id']);
        Mail::to($user->email)->send(new WelcomeEmail($user));
    }
}

// In a controller or callback
dispatch(new SendWelcomeEmail($user->id));

// Or queue for later
dispatch(new SendWelcomeEmail($user->id))->onQueue('default');

use Mlangeni\Machinjiri\Components\Alert;
use Mlangeni\Machinjiri\Components\Button;
use Mlangeni\Machinjiri\Components\Card;
use Mlangeni\Machinjiri\Components\Form;
use Mlangeni\Machinjiri\Components\Input;
use Mlangeni\Machinjiri\Components\Modal;
use Mlangeni\Machinjiri\Components\Nav;
use Mlangeni\Machinjiri\Components\ProgressBar;

// Alert component
$alert = new Alert('Success!', 'success');
echo $alert->render();

// Button component
$button = new Button('Click Me', 'btn-primary');
echo $button->render();

// Form component
$form = new Form('POST', '/submit');
$form->addField('email', 'email');
$form->addField('password', 'password');
echo $form->render();

// Input component
$input = new Input('email', '[email protected]');
echo $input->render();

// Card component
$card = new Card('Title', 'Content');
echo $card->render();

// config/app.php
return [
    'name' => env('APP_NAME', 'Machinjiri'),
    'env' => env('APP_ENV', 'production'),
    'debug' => env('APP_DEBUG', false),
    'key' => env('APP_KEY'),
    
    'timezone' => 'UTC',
    'locale' => 'en',
    
    'url' => env('APP_URL', 'http://localhost'),
];

// config/providers.php
return [
    'providers' => [
        Mlangeni\Machinjiri\App\Providers\AppServiceProvider::class,
        Mlangeni\Machinjiri\App\Providers\AuthServiceProvider::class,
        Mlangeni\Machinjiri\App\Providers\RouteServiceProvider::class,
    ],
    
    'aliases' => [
        'Router' => Mlangeni\Machinjiri\Core\Routing\Router::class,
        'View' => Mlangeni\Machinjiri\Core\Views\View::class,
    ],
];

// config/mail.php
return [
    'driver' => env('MAIL_DRIVER', 'smtp'),
    'host' => env('MAIL_HOST', 'smtp.mailtrap.io'),
    'port' => env('MAIL_PORT', 465),
    'username' => env('MAIL_USERNAME'),
    'password' => env('MAIL_PASSWORD'),
    'from' => [
        'address' => env('MAIL_FROM_ADDRESS', '[email protected]'),
        'name' => env('MAIL_FROM_NAME', 'Machinjiri'),
    ],
];

use Mlangeni\Machinjiri\Machinjiri\Machinjiri;

// Get application instance
$app = Machinjiri::getInstance();

// Bind service
$app->bind('key', function($app) {
    return new Service();
});

// Resolve service
$service = $app->resolve('key');

// Check environment
$isProduction = Machinjiri::getEnvironment() === 'production';
$isDevelopment = Machinjiri::getEnvironment() === 'development';

// Get configuration
$config = $app->config('app.timezone');

use Mlangeni\Machinjiri\Core\Routing\Router;

// HTTP Methods
Router::get($pattern, $handler, $name = null, $options = []);
Router::post($pattern, $handler, $name = null, $options = []);
Router::put($pattern, $handler, $name = null, $options = []);
Router::delete($pattern, $handler, $name = null, $options = []);
Router::patch($pattern, $handler, $name = null, $options = []);
Router::any($pattern, $handler, $name = null, $options = []);
Router::match($methods, $pattern, $handler, $name = null, $options = []);

// Special Routes
Router::ajax($pattern, $handler, $name = null, $options = []);
Router::traditional($pattern, $handler, $name = null, $options = []);

// Route Groups
Router::group($attributes, $callback);

// Middleware
Router::middleware($middleware, $callback);

// CORS
Router::cors($config, $callback);

// URL Generation
Router::route($name, $parameters = []);
Router::absoluteRoute($name, $parameters = []);

// Dispatching
Router::dispatch();

use Mlangeni\Machinjiri\Core\Views\View;

// Create and render
View::make($view, $data = []);
View::make($view, $data)->render();
View::make($view, $data)->display();

// Share data globally
View::share($key, $value);

// Template functions (in view files)
<%= $variable %>              // Output variable
<% section('name') %>...<%endsection %>   // Define section
<% yield('name') %>           // Output section
<% extend('layout') %>        // Extend layout
<% 

// In route handler or controller
public function handle($request, $response)
{
    // Get data
    $all = $request->all();
    $input = $request->input('name');
    $only = $request->only(['email', 'password']);
    $except = $request->except(['password']);
    
    // Check methods
    $isPost = $request->isPost();
    $isJson = $request->isJson();
    $isAjax = $request->isAjax();
    
    // Get headers
    $auth = $request->header('Authorization');
    $headers = $request->headers();
    
    // Files
    $file = $request->file('avatar');
    $files = $request->files();
    
    // Server info
    $method = $request->method();
    $uri = $request->uri();
    $path = $request->path();
}

// In route handler or controller
public function handle($request, $response)
{
    // Simple responses
    return "String response";
    
    // JSON response
    return $response->json(['data' => $data]);
    
    // Redirect
    return $response->redirect('/home');
    return $response->redirectBack();
    
    // View response
    return view('page', ['data' => $data]);
    
    // File download
    return $response->download('/path/to/file');
    
    // Set headers
    $response->header('X-Custom', 'value');
    
    // Set status
    $response->status(201);
    
    // Cookies
    $response->cookie('name', 'value', 3600);
}

use Mlangeni\Machinjiri\Core\Database\QueryBuilder;
use Mlangeni\Machinjiri\Core\Database\DatabaseConnection;

// Get connection
$conn = DatabaseConnection::connection('mysql');

// Query builder
$result = QueryBuilder::table('users')
    ->select(['id', 'name', 'email'])
    ->where('active', true)
    ->whereIn('role', ['admin', 'moderator'])
    ->orderBy('name', 'asc')
    ->limit(10)
    ->get();

// Retrieve single
$user = QueryBuilder::table('users')->where('id', 5)->first();

// Insert
QueryBuilder::table('users')->insert([
    'name' => 'John',
    'email' => '[email protected]',
]);

// Update
QueryBuilder::table('users')
    ->where('id', 5)
    ->update(['name' => 'Jane']);

// Delete
QueryBuilder::table('users')->where('id', 5)->delete();

// Aggregate
$count = QueryBuilder::table('users')->count();
$max = QueryBuilder::table('posts')->max('views');
$avg = QueryBuilder::table('orders')->avg('amount');

// Exists
$exists = QueryBuilder::table('users')->where('email', $email)->exists();

use Mlangeni\Machinjiri\Core\Exceptions\MachinjiriException;

try {
    // Your code
    if (!$user) {
        throw new MachinjiriException('User not found', 404);
    }
} catch (MachinjiriException $e) {
    // Access error details
    $message = $e->getMessage();
    $code = $e->getCode();
    
    // Display error (different in dev/prod)
    $e->show();
    
    // Or handle manually
    return view('error', ['error' => $e->getMessage()]);
}

// tests/Unit/UserTest.php
namespace Mlangeni\Machinjiri\Tests\Unit;

use PHPUnit\Framework\TestCase;

class UserTest extends TestCase
{
    public function testUserCreation()
    {
        $user = User::create([
            'name' => 'John',
            'email' => '[email protected]',
            'password' => password_hash('secret', PASSWORD_BCRYPT),
        ]);
        
        $this->assertIsNotNull($user->id);
        $this->assertEquals('John', $user->name);
    }
}
bash
php artisan server:start
bash
# Create migration
php artisan make:migration create_users_table

# Run migrations
php artisan migrate

# Rollback
php artisan migrate:rollback
bash
php artisan make:seeder UserSeeder
php artisan db:seed
bash
php artisan make:job SendWelcomeEmail
bash
php artisan queue:work