PHP code example of fragment / elemental

1. Go to this page and download the library: Download fragment/elemental 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/ */

    

fragment / elemental example snippets




class MailService {
    public function __construct(private MailerAgent $mailer) {
    }
}

// Inside some other class

class UserController {
    public function sendMail(MailService $mailService)
    {
        $mailService->sendMail();
    }
}


app()->bind(MailService::class, function () {
    // Run some logic, for example, decide on the mail agent to be passed to its constructor depending on some factors.
    return new MailService(app()->make(MailAgent::class));
});


app()->singleton(DatabaseConnection::class, function () {
    return new DatabaseConnection('localhost', 'username', 'password');
});

// Later in the code
$databaseConnection1 = app()->make(DatabaseConnection::class);
$databaseConnection2 = app()->make(DatabaseConnection::class);

// $databaseConnection1 and $databaseConnection2 will reference the same instance




namespace App\Bootstrap;

use App\Services\Auth;

class AppServiceProvider
{
    public function register(): void
    {
        app()->singleton(Auth::class, function () {
            return new Auth();
        });
    }

    public function boot(): void
    {
        // Additional initialization logic can be placed here
    }
}


use App\Services\MailService;

$mailService=  app()->make(MailService::class);

use Core\Main\Application;
use App\Services\MailService;

$mailService =  Application::instance()->make(MailService::class);



use App\Controllers\AuthController;
use Core\Facade\Route;

Route::get("/settings", function () {
    // handling logic goes here
});

Route::post("/register", [AuthController::class, "register"]);

Route::get('/user/{id}', function (string $id) {
    return 'User ' . $id;
});

Route::get("/story/{id}", function ($id) {/*...*/});


Route::post("story/edit/{id}", [StoryController::class, "edit"]);

Route::get("story/{story_id}/comment/{comment_id}", [StoryController::class, "comment"]);



use Core\Request\Request;

Route::get('/users', function (Request $request) {
    // ...
});

use App\Models\User;

Route::get('/users/{user}', function  (User  $user) {

return  $user->email;

});

use App\Models\User;

Route::get('/users/{user:email}', function  (User $user) {
    return  $user;
});

Route::fallback(function () {
    // ...
});


use App\Services\Auth;

namespace App\Controllers;

class AuthController
{
    public function showRegister()
    {
        return view("Register")->withLayout("layouts.DashboardLayout");
    }

    public function logout()
    {
        Auth::logout();
        redirect("/");
    }
}

use App\Controllers\UserController;

Route::get("/register", [AuthController::class, "showRegister"]);



namespace App\Controllers;

use Core\Database\Database;

class UserController
{
    /**
    * Create a new controller instance.
    */
    public function __construct(
        public Database $db,
    ) {}
}



namespace App\Controllers;

use Core\Request\Request;
use App\Services\Auth;

class StoryController
{
    public function create(Request $request)
    {
        $data = $request->data();
        $user = Auth::user();
        $story = Story::create([...]);

        return redirect("/story/$story->id");
    }
}

Route::post("story/update/{id}", [StoryController::class, "update"]);



namespace App\Controllers;
use Core\Request\Request;

class StoryController
{
    public function update(string $id, Request $request)
    {
        // Update the story...

        return redirect("/story/$story->id");
    }
}



namespace App\Controllers;

use App\Models\Category;
use Core\Request\Request;

class CategoryController
{
    public function store(Request $request)
    {
        $name = $request->data()["name"];
        $category = Category::where(["name" => $name]);

        if ($category) {
            return view("Category", ["categories" => Category::all(), "msg" => "Category already exists!"])->withLayout("layouts.DashboardLayout");
        }

        Category::create($request->data());

        redirect("/category");
    }
}

Route::post("story/update/{id}", [StoryController::class, "update"]);



namespace App\Controllers;
use Core\Request\Request;

class StoryController
{
    public function update(string $id, Request $request)
    {
        // Update the story...
        return redirect("/story/$story->id");
    }
}

$data =  $request->data();

$name=  $request->data()["name"];

$headers = $request->headers();

$method = $request->method();

$uri = $request->uri();

$cookies = $request->cookies();

$content = $request->rawContent();

$files= $request->files();

$ipAddress  =  $request->ip();

$port=  $request->port();

$contentType = $request->contentType();

$query= $request->queryString();

$text= $request->text();

$js= $request->js();

$js= $request->html();

$jsonData = $request->json();

$xmlData = $request->xml();

Route::get('/', function  () {
	return  'Hello World';
});

Route::get('/', function  () {
	return [1, 2, 3];
});


use Core\Response\Response;

Route::get('/home', function(Response $response) {
	$response->setHeader("content-type", "text/plain")
			->setStatusCode(200)
			->setContent("Hello World");

	return  response;
});


use Core\Response\Response;

class UserController {
	public function register(Response $response){
		$response->setHeader("x-is_register", "true");
		return view("Register");
	}
}

	$response->setContent("...");

	$response->appendContent("...");

	$response->setHeader("content-type", "text/plain");

	$response->setHeaders(["content-type" => "text/html", ...]);

	$response->setStatusCode(301);

use Core\Response\Response;

Route::get('/dashboard', function  () {
	return Response::redirect('home/dashboard');
});

use Core\Response\Response;

Route::post('/story/create', function  () {
	if(!some condition)
		return redirect('/story', 204);
});

use Core\Response\Response;

Route::post('/post', function  () {
	$post = (...);
	return Response::JSON($post, 201, ["header"=>"value"]);
});



namespace App\Middlewares;

use App\Services\Auth;
use Closure;
use Core\Request\Request;

class IsAuthenticated
{
    public function handle(Request $request, Closure $next)
    {
        if (!(/* authentication logic */)) {
            return redirect("/login");
        }

        return $next($request);
    }
}



namespace App\Middlewares;

use Closure;
use Core\Request\Request;

class AfterMiddleware
{
    public function handle(Request $request, Closure $next)
    {
        $response = $next($request);
        // Perform action

        return $response;
    }
}

Route::get('/profile', function () {
    // ...
})->middleware(IsAuthenticated::class);

Route::get('/', function () {
    // ...
})->middleware([First::class, Second::class]);

Route::group(["middleware" => [HasSession::class]], function () {
    Route::get("/", [StoryController::class, "index"]);
    Route::get("/story/{story}", [StoryController::class, "show"]);
});

Route::group(["middleware" => [HasSession::class]], function () {
    Route::get("/", [StoryController::class, "index"]);
    Route::get("/story/{story}", [StoryController::class, "show"]);

    Route::group(["middleware" => [IsAuth::class, Log::class]], function () {
        Route::get("/compose", [StoryController::class, "compose"]);
        Route::post("/compose", [StoryController::class, "create"]);
    });
});

<html>
<body>
  <h1>Hello, <?= $name 

Route::get('/', function () {
  return view('Welcome', ['name' => 'Ahmed']);
});

Route::get('/', function () {
  return View::make("Post", $params);
});

return view('layouts.MainLayout', $data);

public function compose()
{
  return view("Compose")->withLayout("layouts.DashboardLayout");
}

<a class="logo" href="/">
  <span class="logo-img">
    <img src="logo.png" class="logo-text">
    LOGO
  </span>
</a>

<div>
  <?= component("components.Logo") 



return [
    "db" => [
        "driver" => getenv("DB_DRIVER") ?? "mysql",
        "host" => getenv("DB_HOST") ?? $_SERVER['SERVER_ADDR'],
        "port" => getenv("DB_PORT") ?? "3306",
        "database" => getenv("DB_DATABASE") ?? "elemental",
        "username" => getenv("DB_USERNAME") ?? "root",
        "password" => getenv("DB_PASSWORD") ?? "",
    ],
];

public function tokens(Database $db) {
    $user_id = 1;

    $sql = "SELECT * FROM access_tokens WHERE user_id = :user_id";

    $stmt = $db->prepare($sql);

    $stmt->bindValue(":user_id", $user_id);
    $stmt->execute();

    $tokens = $stmt->fetchAll();
}



namespace App\Models;

use Core\Model\Model;

class Post extends Model
{
    // ...
}



namespace App\Models;

use Core\Model\Model;

class Post extends Model
{
    protected $tableName = 'elemental_posts';
}



namespace App\Models;

use Core\Model\Model;

class Post extends Model
{
    protected $primaryKey = 'elemental_id';
}

use App\Models\Story;

foreach (Story::all() as $story) {
    echo $story["content"];
}

use App\Models\Story;

foreach (Story::all() as $story) {
    echo $story->content;
}

public static function allWhere(array $conditions, array $options = [], int $fetchMode = PDO::FETCH_ASSOC)

use Core\Request\Request;

class StoryController {

    const PAGE_SIZE = 10;

    public function index(Request $request)
    {
        $search = $request->search;
        $categoryId = $request->category_id;

        $sortBy = $request->sort_by; // ASC or DESC, Default = ASC
        $page = $request->page;
        $orderBy = $request->order_by;

        return Story::allWhere(
            [
                "category_id" => $categoryId,
                "title" => ["LIKE", "%$search$"],
            ],
            [
                "limit" => static::PAGE_SIZE,
                "orderBy" => $orderBy,
                "sortDir" => $sortBy,
                "offset" => ($page - 1) * static::PAGE_SIZE,
            ],
            PDO::FETCH_OBJ
        );
    }
}

$flight = Story::find(1);

$user = User::where(["email" => $email]);
$liked = Like::where(["user_id" => $user->id, "story_id" => $story_id]);



namespace App\Controllers;

use App\Models\Story;
use Core\Request\Request;

class StoryController
{
    public function store(Request $request)
    {
        $story = new Story;
        $story->name = $request->name;
        $story->save();
        return redirect('/story');
    }
}

use App\Models\Story;

$story = Story::create([
    'name' => 'A tale of elemental magic',
]);

use App\Models\Story;

$story = Story::find(10);
$story->name = 'An elemental tale of magic';
$story->save();

use App\Models\Story;

$story = Story::update(10, ["name" => "A tale", "content" => "Once upon a time ...."]);

use App\Models\Story;

$story = Story::find(12);
$story->destroy();

use App\Models\Story;

Story::delete(12);

$user = User::find(10);
$user_data = $user->data();

php candle help



namespace App\Commands;

use App\Models\User;
use App\Service\MailService;
use Core\Console\Command;

class SendEmails extends Command
{
    protected $key = 'mail:send';
    protected $description = 'Send mails to all users';

    public function handle(MailService $mailService): void
    {
        $mailService->send(User::all());
    }
}

php candle mail:send



namespace App\Commands;

use Core\Console\Command;
use Core\Console\Commander;

class Migration extends Command
{
    protected $key = "migrate";
    protected $description = "Custom migration handler.";

    private $commander;

    public function handle(Commander $commander, Database $db)
    {
        $args = $commander->getArgs();

        if (!isset($args[1])) {
            $this->up();
            return;
        }

        switch ($args[1]) {
            case "fresh":
                $this->downThenUp();
                break;
            case "delete":
                $this->down();
                break;
            default:
                $this->up();
        }
    }

    public function up()
    {
        $sql = "CREATE TABLE IF NOT EXISTS users (
            id INT PRIMARY KEY AUTO_INCREMENT,
            username VARCHAR(255) NOT NULL,
            email VARCHAR(255) NOT NULL UNIQUE,
            password VARCHAR(255) NOT NULL,
            bio TEXT,
            image VARCHAR(255),
            created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
        )";

        try {
            $db->exec($sql);
            console_log("Table 'users' created successfully!");
        } catch (\PDOException $e) {
            console_log("Table creation error: " . $e->getMessage());
        }
    }

    public function down()
    {
        $sql = "DROP TABLE IF EXISTS users";

        try {
            $db->exec($sql);
            console_log("Table 'users' deleted successfully!");
        } catch (\PDOException $e) {
            console_log("Table deletion error: " . $e->getMessage());
        }
    }

    public function downThenUp()
    {
        $this->down();
        $this->up();
    }
}


$app = app();

app()->bind(CustomService::class, function () {
	return new CustomService(new anotherService());
});

$service = app()-make(CustomService::class);

dump($value);
dump($user, "user");

dd($value);
dd($user, "user");

console_log($value);
console_log($user, $post, $image, $comment);

return view('Login');


<body>
	<?= component("Logo")

return  redirect('/home');



namespace App\Exceptions;

use Core\Exception\ExceptionHandler;

class Handler extends ExceptionHandler
{
    public function handle($e)
    {
        // Perform some processing here

        // You can customize the handling of exceptions based on your 



class Handler extends ExceptionHandler
{
    public function handle($e)
    {
        if ($e instanceof ModelNotFoundException || $e instanceof RouteNotFoundException) {
            return view("404")->withLayout("layouts.DashboardLayout");
        }

        if ($e instanceof ViewNotFoundException) {
            return view("Home");
        }

        // Handle other specific exceptions as needed
    }
}

$appName = getenv("APP_NAME");

use Core\Config\Config;

class YourClass {

    public function __construct(Config $config) {
        $driver = $config->db["driver"];
        $host = $config->db["host"];
        $port = $config->db["port"];
    }

    // Your other methods or code here
}

// routes.php


use Core\Facade\Route;

Route::get("/register", [AuthController::class, "showRegister"]);
Route::get("/login", [AuthController::class, "showLogin"]);
Route::get("/logout", [AuthController::class, "logout"]);
Route::post("/register", [AuthController::class, "register"]);



use Core\Facade\Facade;
use Core\Services\PaymentGateway;

class PaymentGatewayFacade extends Facade
{
    protected static function getFacadeAccessor()
    {
        return PaymentGateway::class;
    }
}
bash
cd sample-app

php candle ignite
bash
php candle route:list
bash
php candle build:controller UserController
bash
php candle build:middleware IsAuthenticated
bash
php candle build:model Post
bash
php candle ignite
bash
php candle ingite --host=192.168.1.10
bash
php candle ingite --port=8080
bash
php candle ingite --host=192.168.1.10 --port=8080
bash
php candle route:list
bash
php candle build:model Story
bash Copy code
php candle build:controller StoryController
bash
php candle build:middleware HasSession
bash
php candle build:command Migration
bash
php candle migrate
php candle migrate fresh
php candle migrate delete