PHP code example of locky42 / leopard-core

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

    

locky42 / leopard-core example snippets


use Leopard\Core\Container;

$container = new Container();

// Register a service
$container->set('logger', function () {
    return new Logger();
});

// Retrieve the service
$logger = $container->get('logger');

class UserController
{
    // GET /user/about
    public function aboutAction(): string
    {
        return "About page";
    }
    
    // GET /user/profile
    public function getProfileAction(): string
    {
        return "User profile (GET)";
    }
    
    // POST /user/profile
    public function postProfileAction(): string
    {
        return "Update profile (POST)";
    }
    
    // DELETE /user/account
    public function deleteAccountAction(): string
    {
        return "Delete account";
    }
    
    // GET /user (index is special case)
    public function indexAction(): string
    {
        return "User index";
    }
    
    // This method will NOT be routed (no Action suffix)
    public function helperMethod(): string
    {
        return "Not a route";
    }
}

use Leopard\Core\Router;
use Leopard\Core\Attributes\Route;

class TestController
{
    #[Route('/test', method: 'GET')]
    public function test(): string
    {
        return "Hello, world!";
    }
    
    #[Route('/user/{id}', method: 'GET')]
    public function getUser(string $id): string
    {
        return "User ID: $id";
    }
}

$router = new Router($container);
$router->registerController(TestController::class);
$response = $router->dispatch('GET', '/test');

$router = new Router($container);

// Load all controllers from directory
$router->loadControllersFrom(__DIR__ . '/src/Controllers');

// Methods with Action suffix will be auto-registered
// GET /test/about -> TestController::aboutAction()
// POST /test/submit -> TestController::postSubmitAction()

use Leopard\Core\Attributes\Route;

#[Route('/user/{id}', method: 'GET')]
public function getUser(string $id): string
{
    return "User ID: $id";
}

use Leopard\Core\Factory\ContractFactory;

// Define an interface
interface LoggerInterface {
    public function log(string $message): void;
}

// Create an implementation
class FileLogger implements LoggerInterface {
    public function log(string $message): void {
        file_put_contents('app.log', $message . PHP_EOL, FILE_APPEND);
    }
}

// Register the implementation
ContractFactory::register(LoggerInterface::class, FileLogger::class);

// Create instances through the factory
$logger = ContractFactory::create(LoggerInterface::class);
$logger->log('Application started');

// Production logger
class ProductionLogger implements LoggerInterface {
    public function log(string $message): void {
        // Send to external service
    }
}

// Test logger
class TestLogger implements LoggerInterface {
    private array $logs = [];
    
    public function log(string $message): void {
        $this->logs[] = $message;
    }
    
    public function getLogs(): array {
        return $this->logs;
    }
}

// In production
ContractFactory::register(LoggerInterface::class, ProductionLogger::class);

// In tests
ContractFactory::register(LoggerInterface::class, TestLogger::class);

use Leopard\Core\Factory\ContractFactory;
use Leopard\User\Contracts\Models\UserInterface;
use App\Models\User;

// Register user models
ContractFactory::register(UserInterface::class, User::class);

// Use in your application
class UserService {
    public function createUser(array $data): UserInterface {
        $user = ContractFactory::create(UserInterface::class);
        $user->setPassword($data['password']);
        return $user;
    }
}

use Leopard\Core\Factory\ContractFactory;
use Leopard\User\Contracts\Models\UserInterface;
use App\Models\User;

// Registers ContractFactory mapping
// + auto-registers Doctrine resolve-target mapping
ContractFactory::register(UserInterface::class, User::class);

ContractFactory::register(
    UserInterface::class,
    User::class,
    ['fetch' => 'EAGER']
);

   // Good
   ContractFactory::register(UserInterface::class, User::class);
   
   // Bad
   ContractFactory::register('UserInterface', 'User');
   

    // config/contract-mappings.php
   ContractFactory::register(UserInterface::class, User::class);
   ContractFactory::register(LoggerInterface::class, FileLogger::class);

    // bootstrap.php
    

   // Good - flexible
   public function processUser(UserInterface $user) { }
   
   // Bad - tightly coupled
   public function processUser(User $user) { }
   

   class MyTest extends TestCase {
       protected function setUp(): void {
           ContractFactory::clear();
           ContractFactory::register(UserInterface::class, MockUser::class);
       }
       
       protected function tearDown(): void {
           ContractFactory::reset();
       }
   }
   

try {
    $user = ContractFactory::create(UserInterface::class);
} catch (\InvalidArgumentException $e) {
    // Handle: interface not registered
    echo "Error: " . $e->getMessage();
}

use Leopard\Core\View;

$view = new View(__DIR__ . '/src/views');

// Set custom layout
$view->setLayout('layouts/admin');

// Add styles and scripts
$view->addStyle('/assets/css/main.css');
$view->addScript('/assets/js/app.js');

// Configure SEO
$view->getSeo()->setTitle('Welcome Page');
$view->getSeo()->setDescription('This is the homepage');
$view->getSeo()->setKeywords(['php', 'framework', 'leopard']);

// Render view
echo $view->render('site/home', [
    'username' => 'John',
    'data' => ['foo' => 'bar']
]);

// In your layout file (layouts/main.php)
<!DOCTYPE html>
<html>
<head>
    <title><?= $this->getSeo()->getTitle() 

use Leopard\Core\Services\Seo;

$seo = new Seo();

// Basic SEO
$seo->setTitle('My Awesome Page');
$seo->setDescription('A detailed description of my page');
$seo->setCanonicalUrl('https://example.com/page');
$seo->setKeywords(['keyword1', 'keyword2', 'keyword3']);
$seo->setRobots('index, follow');
$seo->setCharset('UTF-8');

// Add custom meta tags
$seo->addMetaTag('author', 'John Doe');
$seo->addMetaTag('viewport', 'width=device-width, initial-scale=1.0');

// Open Graph tags
$seo->addOpenGraphTag('og:title', 'My Awesome Page');
$seo->addOpenGraphTag('og:type', 'website');
$seo->addOpenGraphTag('og:url', 'https://example.com/page');
$seo->addOpenGraphTag('og:image', 'https://example.com/image.jpg');

// Twitter Cards
$seo->addTwitterCard('twitter:card', 'summary_large_image');
$seo->addTwitterCard('twitter:title', 'My Awesome Page');
$seo->addTwitterCard('twitter:description', 'A detailed description');

// Access in templates
echo $seo->getTitle(); // "My Awesome Page"
echo implode(', ', $seo->getKeywords()); // "keyword1, keyword2, keyword3"

// In your layout file
<head>
    <meta charset="<?= $this->getSeo()->getCharset() ?? 'UTF-8' 

use Leopard\Core\Config;

$config = new Config();
$config->load(__DIR__ . '/config/app.yaml');

echo $config->get('database.host'); // Outputs 'localhost'