### Example setUp() Implementation Source: https://github.com/byjg/byjg.github.io/blob/master/docs/php/message-queue-client/connector-interface.md Implement the setUp method to configure the connector using connection details from a provided URI. ```php host = $uri->getHost(); $this->port = $uri->getPort() ?: 5672; $this->username = $uri->getUsername(); $this->password = $uri->getPassword(); $this->vhost = $uri->getPath() ?: "/"; } ``` -------------------------------- ### Initial Project Setup Source: https://github.com/byjg/byjg.github.io/blob/master/docs/devops/n8n-gitops/commands.md Guides through the initial setup of an n8n-gitops project, including creation, configuration, and initial commit. ```bash # 1. Create project n8n-gitops create-project my-project cd my-project # 2. Configure auth n8n-gitops configure --config dev --api-url https://n8n.example.com --api-key KEY # 3. Export workflows n8n-gitops export # uses externalize_code from manifest (default: true) # 4. Commit to git git init git add . git commit -m "Initial export" git tag v1.0.0 ``` -------------------------------- ### Install and Start Demo Service Source: https://github.com/byjg/byjg.github.io/blob/master/docs/php/scriptify/play.md Installs and starts the 'tryme' demo service using Scriptify. This command configures it as a systemd service, specifying the class, bootstrap file, and root directory. ```bash sudo scriptify install --template=systemd tryme \ --class \"\ByJG\Scriptify\Sample\TryMe::process\" \ --bootstrap "vendor/autoload.php" \ --rootdir "./" sudo systemctl start tryme ``` -------------------------------- ### Example: Parent Directory Quick Setup Source: https://github.com/byjg/byjg.github.io/blob/master/docs/php/rest-reference-architecture/getting-started/unattended-setup.md Perform a quick setup by placing the setup.json file in the same directory where you create the new project. This is ideal for project-specific configurations. ```bash # Create config in your projects directory cd ~/projects cat > setup.json << 'EOF' { "namespace": "MyApp", "composer_name": "mycompany/myapp", "install_examples": false } EOF # Create project in the same directory composer -sdev create-project byjg/rest-reference-architecture my-project ^6.1 ``` -------------------------------- ### Quick Start: Project Setup and Initialization Source: https://github.com/byjg/byjg.github.io/blob/master/docs/php/rest-reference-architecture/README.md Use this command to create a new project from the template and start the Docker containers. It also includes running initial database migrations. ```bash # Create your project composer -sdev create-project byjg/rest-reference-architecture my-api ^6.1 # Start containers cd my-api docker compose up -d # Run migrations composer migrate -- --env=dev reset # Your API is ready! curl http://localhost:8080/sample/ping ``` -------------------------------- ### Install Service with Environment Variables Source: https://github.com/byjg/byjg.github.io/blob/master/docs/php/rest-reference-architecture/reference/scriptify.md Install a service and configure environment variables that will be loaded automatically when the service starts. ```bash scriptify install --template=systemd myservice \ --class \"\MyClass::myMethod\" \ --env DB_HOST=localhost \ --env DB_NAME=mydb ``` -------------------------------- ### Complete Example: Wallets and Transactions with Custom Fields Source: https://github.com/byjg/byjg.github.io/blob/master/docs/php/wallets/extending-entities.md A comprehensive example demonstrating the setup, creation, and querying of wallets and transactions with custom fields using extended repositories and services. ```php createWallet('USD', 'user-123', 10000); $wallet = $walletService->getById($walletId); $wallet->setTier('platinum'); $wallet->setLoyaltyPoints(5000); $wallet->setPreferences('{"theme": "dark", "alerts": true}'); $walletRepo->save($wallet); // 3. Create transaction with custom fields $dto = TransactionDTO::create($walletId, 2500) ->setDescription('VIP purchase') ->setCode('VIP'); $transaction = $transactionService->addFunds($dto); $transaction->setExtraProperty('VIP member discount applied'); $transaction->setCustomField(42); $transaction->setMetadata('{"discount": 0.15, "campaign": "summer2024"}'); $transactionRepo->save($transaction); // 4. Query by custom fields $goldWallets = $walletRepo->getByTier('gold'); $transactions = $transactionRepo->getByCustomField(42); // 5. Award loyalty points on transaction $walletRepo->addLoyaltyPoints($walletId, 25); // Add 25 points echo "Transaction {" . $transaction->getTransactionId() . "} created\n"; echo "Extra property: {" . $transaction->getExtraProperty() . "}\n"; echo "Loyalty points: {" . $wallet->getLoyaltyPoints() . "}\n"; ``` -------------------------------- ### Quick Start: Wallet Operations Example Source: https://github.com/byjg/byjg.github.io/blob/master/docs/php/wallets/getting-started.md Demonstrates initializing services, creating a wallet type, creating a user wallet, adding and withdrawing funds, and checking the balance. ```php use ByJG\Wallets\Service\WalletService; use ByJG\Wallets\Service\WalletTypeService; use ByJG\Wallets\Service\TransactionService; use ByJG\Wallets\Entity\WalletTypeEntity; use ByJG\Wallets\Repository\WalletRepository; use ByJG\Wallets\Repository\WalletTypeRepository; use ByJG\Wallets\Repository\TransactionRepository; use ByJG\Wallets\DTO\TransactionDTO; use ByJG\AnyDataset\Db\Factory; // Create database connection $dbDriver = Factory::getDbInstance('mysql://user:pass@localhost/dbname'); // Initialize repositories $walletTypeRepo = new WalletTypeRepository($dbDriver); $transactionRepo = new TransactionRepository($dbDriver); $walletRepo = new WalletRepository($dbDriver); // Initialize services $walletTypeService = new WalletTypeService($walletTypeRepo); $transactionService = new TransactionService($transactionRepo, $walletRepo); $walletService = new WalletService($walletRepo, $walletTypeService, $transactionService); // Create a wallet type (e.g., USD) $walletType = new WalletTypeEntity(); $walletType->setWalletTypeId('USD'); $walletType->setName('US Dollar Wallet'); $walletTypeService->update($walletType); // Create a wallet for a user with an initial balance of $100.00 (10000 cents) $walletId = $walletService->createWallet('USD', 'user-123', 10000, 2); // Add funds: $50.00 (5000 cents) $dto = TransactionDTO::create($walletId, 5000) ->setDescription('Deposit from bank account') ->setCode('DEP'); $transactionService->addFunds($dto); // Withdraw funds: $30.00 (3000 cents) $dto = TransactionDTO::create($walletId, 3000) ->setDescription('Purchase payment') ->setCode('PMT'); $transactionService->withdrawFunds($dto); // Get wallet balance $wallet = $walletService->getById($walletId); echo "Available balance: " . ($wallet->getAvailable() / 100) . " USD\n"; // Output: Available balance: 120 USD ``` -------------------------------- ### Complete User Model and Service Setup Source: https://github.com/byjg/byjg.github.io/blob/master/docs/php/authuser/mappers.md Example demonstrating a custom user model with various field mappers and the initialization of the UsersService with repositories. ```php strtolower(trim((string) $value))))] protected ?string $email = null; } $dbDriver = DbFactory::getDbInstance('mysql://user:pass@localhost/app'); $db = DatabaseExecutor::using($dbDriver); $usersRepo = new UsersRepository($db, CustomUserModel::class); $propsRepo = new UserPropertiesRepository($db, \ByJG\Authenticate\Model\UserPropertiesModel::class); $users = new UsersService($usersRepo, $propsRepo, LoginField::Username); ``` -------------------------------- ### Complete Authentication and Session Management Example Source: https://github.com/byjg/byjg.github.io/blob/master/docs/php/authuser/session-context.md A full example demonstrating user authentication, session context initialization, login, storing session data, and protecting pages. Includes setup for repositories and services. ```php isValidUser($_POST['username'], $_POST['password']); if ($user !== null) { $sessionContext->registerLogin($user->getUserid()); $sessionContext->setSessionData('login_time', time()); header('Location: /dashboard'); exit; } } // Protected pages if (!$sessionContext->isAuthenticated()) { header('Location: /login'); exit; } $userId = $sessionContext->userInfo(); $user = $users->getById($userId); $loginTime = $sessionContext->getSessionData('login_time'); echo "Welcome, " . $user->getName(); echo "Logged in at: " . date('Y-m-d H:i:s', $loginTime); // Logout if (isset($_POST['logout'])) { $sessionContext->registerLogout(); header('Location: /login'); exit; } ``` -------------------------------- ### Example: Personal Defaults Setup Source: https://github.com/byjg/byjg.github.io/blob/master/docs/php/rest-reference-architecture/getting-started/unattended-setup.md Configure personal defaults by creating a setup.json file in your home directory. Projects created subsequently will automatically use these settings. ```bash # Linux/Mac mkdir -p ~/.rest-reference-architecture cat > ~/.rest-reference-architecture/setup.json << 'EOF' { "git_user_name": "John Doe", "git_user_email": "john.doe@example.com", "install_examples": false } EOF # Now create projects anywhere - they'll use your defaults cd ~/projects composer -sdev create-project byjg/rest-reference-architecture project1 ^6.1 composer -sdev create-project byjg/rest-reference-architecture project2 ^6.1 ``` -------------------------------- ### Verify Installation with Sample Ping Endpoint Source: https://github.com/byjg/byjg.github.io/blob/master/docs/php/rest-reference-architecture/getting-started/installation.md Send a request to the sample ping endpoint to verify the installation if examples were included. ```shell curl http://localhost:8080/sample/ping ``` -------------------------------- ### Start SSE with Message Handler Source: https://github.com/byjg/byjg.github.io/blob/master/docs/js/yaj-sse/api-reference.md Example of starting SSE and logging received data. Ensure the server URL is correct. ```javascript var sse = new SSE('http://example.com/sse-server.php', { onMessage: function(e) { console.log(e.data); } }); sse.start(); ``` -------------------------------- ### Create Migration Table and Check Version Source: https://github.com/byjg/byjg.github.io/blob/master/docs/php/migration/cli-usage.md Example of initial setup for migrations: first, create the version tracking table using the 'create' command with specified connection and path, then check the current version. ```bash # 1. Create the version tracking table vendor/bin/migrate create \ --connection mysql://root:password@localhost/myapp \ --path ./database/migrations # 2. Check current version vendor/bin/migrate version -c mysql://root:password@localhost/myapp ``` -------------------------------- ### Example: CI/CD Environment Variable Setup Source: https://github.com/byjg/byjg.github.io/blob/master/docs/php/rest-reference-architecture/getting-started/unattended-setup.md Utilize the SETUP_JSON environment variable for unattended setup in CI/CD environments. Store your configuration file in a designated location and reference it during project creation. ```bash # Store config anywhere cat > /etc/ci-configs/rest-setup.json << 'EOF' { "git_user_name": "CI Bot", "git_user_email": "ci@company.com", "namespace": "AutoDeployApp", "install_examples": false } EOF # Use it with environment variable SETUP_JSON=/etc/ci-configs/rest-setup.json composer -sdev create-project byjg/rest-reference-architecture production-app ^6.1 ``` -------------------------------- ### Dockerfile for Installing Additional Packages Source: https://github.com/byjg/byjg.github.io/blob/master/docs/devops/docker-php/dockerfile.md This example demonstrates how to install additional system packages and PHP extensions in your Docker image. It temporarily switches to the root user to perform installations and then switches back to the `app` user. Always switch back to the non-root user for security. ```dockerfile FROM byjg/php:8.3-cli # Switch to root to install packages USER root RUN apk add --no-cache imagemagick imagemagick-dev # Install PHP extensions if needed RUN pecl install imagick && \ echo "extension=imagick.so" > /etc/php/conf.d/imagick.ini # Switch back to app user USER app # Copy application with proper ownership COPY --chown=app:app . /app WORKDIR /app RUN composer install --no-dev --optimize-autoloader ``` -------------------------------- ### Quick Start: PHP Wallets Usage Source: https://github.com/byjg/byjg.github.io/blob/master/docs/php/wallets/README.md Demonstrates initializing the wallet service, creating a wallet type, managing funds (adding, withdrawing, reserving), and retrieving wallet balances. Requires database connection setup. ```php use ByJG\Wallets\Service\WalletService; use ByJG\Wallets\Service\WalletTypeService; use ByJG\Wallets\Service\TransactionService; use ByJG\Wallets\Entity\WalletTypeEntity; use ByJG\Wallets\Repository\WalletRepository; use ByJG\Wallets\Repository\WalletTypeRepository; use ByJG\Wallets\Repository\TransactionRepository; use ByJG\Wallets\DTO\TransactionDTO; use ByJG\AnyDataset\Db\Factory; // Initialize database connection $dbDriver = Factory::getDbInstance('mysql://user:pass@localhost/dbname'); // Initialize repositories $walletTypeRepo = new WalletTypeRepository($dbDriver); $transactionRepo = new TransactionRepository($dbDriver); $walletRepo = new WalletRepository($dbDriver); // Initialize services $walletTypeService = new WalletTypeService($walletTypeRepo); $transactionService = new TransactionService($transactionRepo, $walletRepo); $walletService = new WalletService($walletRepo, $walletTypeService, $transactionService); // Create a wallet type $walletType = new WalletTypeEntity(); $walletType->setWalletTypeId('USD'); $walletType->setName('US Dollar'); $walletTypeService->update($walletType); // Create a wallet with $100.00 initial balance (10000 cents) $walletId = $walletService->createWallet('USD', 'user-123', 10000, 2); // Add funds: $50.00 $transaction = $transactionService->addFunds( TransactionDTO::create($walletId, 5000) ->setDescription('Deposit from bank account') ); // Withdraw funds: $30.00 $transaction = $transactionService->withdrawFunds( TransactionDTO::create($walletId, 3000) ->setDescription('Purchase payment') ); // Reserve funds for pending withdrawal: $20.00 $reserve = $transactionService->reserveFundsForWithdraw( TransactionDTO::create($walletId, 2000) ->setDescription('Pre-authorization') ); // Accept the reservation $transactionService->acceptFundsById($reserve->getTransactionId()); // Get wallet balance $wallet = $walletService->getById($walletId); echo "Available: " . ($wallet->getAvailable() / 100) . " USD\n"; ``` -------------------------------- ### Initialize SSE Client and Start Connection Source: https://github.com/byjg/byjg.github.io/blob/master/docs/js/yaj-sse/README.md Instantiate the SSE client with a server URL and an onMessage handler, then start the connection. This is the basic client-side setup for receiving SSE messages. ```javascript var sse = new SSE('http://example.com/sse-server.php', { onMessage: function(e){ console.log("Message:", e.data); } }); sse.start(); ``` -------------------------------- ### Set Up Complex Environment Configuration in PHP Source: https://github.com/byjg/byjg.github.io/blob/master/docs/php/config/advanced-features.md Illustrates the use of the fluent API to define a multi-level environment setup with inheritance and caching. This example shows how to create base, development, staging, and production environments. ```php setAsAbstract(); // Development environment inherits from base $dev = Environment::create('dev') ->inheritFrom($base); // Staging environment with cache $staging = Environment::create('staging') ->inheritFrom($dev) ->withCache( new FileSystemCacheEngine('/tmp/cache/staging'), CacheModeEnum::multipleFiles ); // Production environment with optimized cache and marked as final $prod = Environment::create('prod') ->inheritFrom($staging) ->withCache( new FileSystemCacheEngine('/tmp/cache/prod'), CacheModeEnum::singleFile ) ->setAsFinal(); // Create definition with all environments $definition = (new Definition()) ->withConfigVar('APP_ENV') ->addEnvironment($base) ->addEnvironment($dev) ->addEnvironment($staging) ->addEnvironment($prod); // Build the container $container = $definition->build(); ``` -------------------------------- ### Clone Repository and Setup Development Environment Source: https://github.com/byjg/byjg.github.io/blob/master/docs/js/jquery-sse/references.md Instructions for cloning the project repository and setting up a local development environment using Docker for PHP. Assumes Node.js is installed for potential dependency management. ```bash # Clone the repository git clone https://github.com/byjg/jquery-sse.git # Install dependencies (if any) npm install # Run examples docker run -it --rm -p 8080:80 -v $PWD:/var/www/html byjg/php:7.4-fpm-nginx ``` -------------------------------- ### Full Dockerfile Configuration Example Source: https://github.com/byjg/byjg.github.io/blob/master/docs/devops/docker-php/dockerfile.md A comprehensive Dockerfile example showcasing various configuration options, including environment variables for debugging, web server settings, SSL/TLS, and disabling unnecessary PHP modules. It copies the application, sets the working directory, and installs Composer dependencies. ```dockerfile FROM byjg/php:8.3-cli # Enable verbose mode for debugging # ENV VERBOSE="true" # Web server configuration (for fpm-nginx/fpm-apache) ENV NGINX_ROOT=/var/www/html ENV PHP_CONTROLLER=/index.php # SSL/TLS configuration # ENV NGINX_SSL_CERT=/path/to/ssl.crt # ENV NGINX_SSL_CERT_KEY=/path/to/ssl.key # Disable unnecessary modules for better performance # ENV DISABLEMODULE_bcmath=1 # ENV DISABLEMODULE_ctype=1 # ENV DISABLEMODULE_curl=1 # ENV DISABLEMODULE_dba=1 # ENV DISABLEMODULE_dom=1 # ENV DISABLEMODULE_fileinfo=1 # ENV DISABLEMODULE_ftp=1 # ENV DISABLEMODULE_gd=1 # ENV DISABLEMODULE_gettext=1 # ENV DISABLEMODULE_iconv=1 # ENV DISABLEMODULE_intl=1 # ENV DISABLEMODULE_mbstring=1 # ENV DISABLEMODULE_openssl=1 # ENV DISABLEMODULE_pcntl=1 # ENV DISABLEMODULE_pdo=1 # ENV DISABLEMODULE_posix=1 # ENV DISABLEMODULE_session=1 # ENV DISABLEMODULE_shmop=1 # ENV DISABLEMODULE_simplexml=1 # ENV DISABLEMODULE_soap=1 # ENV DISABLEMODULE_sockets=1 # ENV DISABLEMODULE_sqlite3=1 # ENV DISABLEMODULE_tokenizer=1 # ENV DISABLEMODULE_xml=1 # ENV DISABLEMODULE_xmlwriter=1 # ENV DISABLEMODULE_zip=1 # ENV DISABLEMODULE_exif=1 # ENV DISABLEMODULE_mysqlnd=1 # ENV DISABLEMODULE_pdo_dblib=1 # ENV DISABLEMODULE_pdo_pgsql=1 # ENV DISABLEMODULE_pdo_sqlite=1 # ENV DISABLEMODULE_phar=1 # ENV DISABLEMODULE_xmlreader=1 # ENV DISABLEMODULE_xsl=1 # ENV DISABLEMODULE_mysqli=1 # ENV DISABLEMODULE_pdo_mysql=1 # ENV DISABLEMODULE_igbinary=1 # ENV DISABLEMODULE_memcached=1 # ENV DISABLEMODULE_redis=1 # ENV DISABLEMODULE_msgpack=1 # ENV DISABLEMODULE_xdebug=1 # ENV DISABLEMODULE_yaml=1 # ENV DISABLEMODULE_mcrypt=1 # ENV DISABLEMODULE_mongodb=1 # Copy application with proper ownership COPY --chown=app:app . /app WORKDIR /app # Install dependencies RUN composer install --no-dev --optimize-autoloader ``` -------------------------------- ### Install uv and EasyHAProxy Source: https://github.com/byjg/byjg.github.io/blob/master/docs/devops/docker-easy-haproxy/getting-started/native.md Installs the uv tool and then installs easy-haproxy as a tool, making it available in ~/.local/bin. ```bash # Install uv (if not already installed) curl -LsSf https://astral.sh/uv/install.sh | sh # Install easyhaproxy as a tool uv tool install easyhaproxy # Make sure ~/.local/bin is in PATH (one-time setup) uv tool update-shell ``` -------------------------------- ### Create Migration Version Table Source: https://github.com/byjg/byjg.github.io/blob/master/docs/php/migration/cli-usage.md Use the 'create' or 'install' command to set up the migration version tracking table in your database. This is a one-time setup step. ```bash vendor/bin/migrate create --connection [options] # or vendor/bin/migrate install --connection [options] ``` ```bash vendor/bin/migrate create -c mysql://user:pass@localhost/mydb ``` -------------------------------- ### Docker and Migration Setup for Testing Source: https://github.com/byjg/byjg.github.io/blob/master/docs/php/wallets/README.md Provides bash commands to start a MySQL Docker container, run database migrations using a provided path, and then execute PHPUnit tests. ```bash # Start MySQL container docker run --name mysql-container --rm \ -e MYSQL_ROOT_PASSWORD=password \ -p 3306:3306 -d mysql:8.0 # Run migrations vendor/bin/migrate up mysql://root:password@localhost/test -path=db # Run tests vendor/bin/phpunit ``` -------------------------------- ### Quick Start: Docker Mode Source: https://github.com/byjg/byjg.github.io/blob/master/docs/devops/docker-easy-haproxy/getting-started/native.md Starts EasyHAProxy in Docker discovery mode. ```bash easy-haproxy --discover docker ``` -------------------------------- ### Quick Start: Kubernetes Mode Source: https://github.com/byjg/byjg.github.io/blob/master/docs/devops/docker-easy-haproxy/getting-started/native.md Starts EasyHAProxy in Kubernetes discovery mode. ```bash easy-haproxy --discover kubernetes ``` -------------------------------- ### Quick Start Examples for ShortID Source: https://github.com/byjg/byjg.github.io/blob/master/docs/php/shortid/README.md Demonstrates basic usage of the ShortID library, including creating IDs from numbers, UUIDs, hex, and generating random IDs, as well as retrieving the original number. ```php beginTransaction(IsolationLevelEnum::READ_COMMITTED); ``` -------------------------------- ### Install AnyDataset Source: https://github.com/byjg/byjg.github.io/blob/master/docs/php/anydataset/README.md Install the AnyDataset library using Composer. ```bash composer require "byjg/anydataset" ``` -------------------------------- ### Basic Migration Setup and Execution Source: https://github.com/byjg/byjg.github.io/blob/master/docs/php/migration/api-reference.md Demonstrates how to set up a basic migration process by registering a database handler, creating a Migration instance with a URI and migration folder, and initiating an update. ```php $uri = new \ByJG\Util\Uri('mysql://user:pass@localhost/database'); \ByJG\DbMigration\Migration::registerDatabase(\ByJG\DbMigration\Database\MySqlDatabase::class); $migration = new \ByJG\DbMigration\Migration($uri, '/migrations'); $migration->update(); ``` -------------------------------- ### Example: Complete Release Process for v0.3.0 Source: https://github.com/byjg/byjg.github.io/blob/master/docs/devops/n8n-gitops/release-process.md A comprehensive example demonstrating the entire release process for version 0.3.0, from updating the changelog to creating the GitHub release. ```bash # 1. Update CHANGELOG.md # Add section for [0.3.0] with release notes # 2. Commit changes git add CHANGELOG.md git commit -m "Release v0.3.0" git push origin main # 3. Create and push tag (this determines the version) git tag -a v0.3.0 -m "Release v0.3.0" git push origin v0.3.0 # 4. Wait for GitHub Actions to complete # Monitor at: https://github.com/YOUR_USERNAME/n8n-gitops/actions # 5. Create GitHub release gh run download --name n8n-gitops-linux gh release create v0.3.0 \ --title "n8n-gitops v0.3.0" \ --notes-file <(sed -n "/## \[0.3.0]/,/## \[/",/p" CHANGELOG.md | head -n -1) \ n8n-gitops-linux/n8n-gitops#n8n-gitops-linux ``` -------------------------------- ### Traditional Setup: Accessing Configuration Source: https://github.com/byjg/byjg.github.io/blob/master/docs/php/config/README.md Access configuration values from the built container using the get() method. This is done after the traditional setup is complete. ```php // 3. Use the configuration values $appName = $container->get('app_name'); // "My Application" $dbHost = $container->get('database')['host']; // "localhost" ``` -------------------------------- ### Quick Start: Static Mode Source: https://github.com/byjg/byjg.github.io/blob/master/docs/devops/docker-easy-haproxy/getting-started/native.md Sets up a configuration file for static mode and starts EasyHAProxy to discover services in the specified directory. ```bash mkdir -p ~/easyhaproxy/static cat > ~/easyhaproxy/static/config.yml <addEnvironment($dev) ->addEnvironment($prod); // Build with the current environment (using APP_ENV environment variable) $container = $definition->build(); ``` -------------------------------- ### Set Up Environment and Create New Project Source: https://github.com/byjg/byjg.github.io/blob/master/blog/2025-11-17-complete-php-ecosystem-zero-to-production/index.md Initializes the development environment by downloading the loader script and setting up a new PHP REST API project. It then starts the project in detached Docker mode. ```bash # Set up environment (one time) /bin/bash -c "$(curl -fsSL https://shellscript.download/install/loader)" load.sh docker load.sh php-docker -- 8.4 # Create new project load.sh php-rest-api -- my-shop-api \ --namespace=MyShop \ --name=mycompany/shop-api cd my-shop-api docker-compose up -d ``` -------------------------------- ### Manual Initialization of Config Facade Source: https://github.com/byjg/byjg.github.io/blob/master/docs/php/config/config-facade.md Demonstrates how to manually initialize the Config facade by creating environments, a definition, and then calling Config::initialize(). ```php addEnvironment($dev) ->addEnvironment($prod); // Initialize Config facade with the definition and current environment $env = getenv('APP_ENV') ?: 'dev'; Config::initialize($definition, $env); ``` -------------------------------- ### Pest PHP Example with OpenApiValidation Source: https://github.com/byjg/byjg.github.io/blob/master/docs/php/swagger-test/trait-usage.md An example demonstrating the use of the OpenApiValidation trait within the Pest PHP testing framework. It includes setup using `beforeEach` and a test case for an API endpoint. ```php // Pest PHP example use ByJG\ApiTools\OpenApiValidation; use ByJG\ApiTools\Base\Schema; use ByJG\ApiTools\ApiRequester; uses(OpenApiValidation::class); beforeEach(function () { $this->setSchema(Schema::fromFile('openapi.json')); }); test('get pet endpoint', function () { $request = new ApiRequester(); $request ->withMethod('GET') ->withPath('/pet/1'); $this->sendRequest($request); }); ``` -------------------------------- ### Complete Example with Custom User Model Source: https://github.com/byjg/byjg.github.io/blob/master/docs/php/authuser/custom-fields.md Demonstrates initializing and using the UsersService with a custom user model, including saving and retrieving users. ```php setName('Jane Smith'); $user->setEmail('jane@example.com'); $user->setUsername('janesmith'); $user->setPassword('SecurePass123'); $user->setPhone('+1-555-5678'); $user->setDepartment('Marketing'); $user->setTitle('Marketing Director'); $savedUser = $users->save($user); // Retrieve and update $user = $users->getById($savedUser->getUserid()); $user->setTitle('VP of Marketing'); $users->save($user); ``` -------------------------------- ### Start Docker Compose and Set Environment Variables Source: https://github.com/byjg/byjg.github.io/blob/master/docs/php/anydataset-nosql/tests.md Starts the local testing infrastructure using Docker Compose and sets environment variables for connecting to local services. This is the initial setup for local testing. ```bash # Start the test infrastructure (MongoDB, MinIO for S3, DynamoDB Local) docker compose up -d # Set environment variables for connecting to the local services export MONGODB_CONNECTION="mongodb://127.0.0.1/test" export S3_CONNECTION="s3://aaa:12345678@us-east-1/mybucket?create=true&endpoint=http://127.0.0.1:4566" export DYNAMODB_CONNECTION="dynamodb://accesskey:secretkey@us-east-1/tablename?endpoint=http://127.0.0.1:8000" # Run the tests vendor/bin/phpunit ``` -------------------------------- ### Example Deployment Output Source: https://github.com/byjg/byjg.github.io/blob/master/docs/devops/n8n-gitops/deployment.md A comprehensive example of the output during a successful deployment, illustrating the steps from planning to execution and state management. ```bash Deploying workflows from /path/to/project Using git ref: v1.0.0 Target: https://n8n.example.com Loaded manifest: 2 workflow(s) Fetching remote workflows... Found 1 remote workflow(s) Deployment plan: + CREATE: New Payment Workflow ⟳ REPLACE: Existing Data Sync ✓ Include: scripts/Existing_Data_Sync/process.py Executing deployment... Creating: New Payment Workflow... ✓ Created with ID: abc123 Activating workflow... ✓ Activated Replacing: Existing Data Sync... Deleting old workflow... ✓ Old workflow deleted Creating new workflow... ✓ Created with ID: def456 Deactivating workflow... ✓ Deactivated ✓ Deployment successful! ``` -------------------------------- ### RowArray Usage Example Source: https://github.com/byjg/byjg.github.io/blob/master/docs/php/anydataset/row.md Shows how to create and use a RowArray object, including getting, setting, and appending values to fields. ```php 1, 'name' => 'John']); // or $row = new RowArray(['id' => 1, 'name' => 'John']); $row->get('id'); // 1 $row->set('name', 'Mary'); // Changes name to Mary $row->set('tags', 'php', true); // Creates tags field with 'php' $row->set('tags', 'database', true); // Appends 'database' to tags, making it an array ``` -------------------------------- ### Setup Docker Buildx for Multi-Platform Builds Source: https://github.com/byjg/byjg.github.io/blob/master/docs/devops/docker-php/building.md Initialize Docker Buildx for building multi-platform images. This is typically a one-time setup. ```bash docker run --privileged --rm tonistiigi/binfmt --install all docker buildx create --name mybuilder --use docker buildx inspect --bootstrap ``` -------------------------------- ### Basic API Test Example Source: https://github.com/byjg/byjg.github.io/blob/master/docs/php/rest-reference-architecture/guides/testing.md A simple test case demonstrating how to make a GET request and expect a 200 status code. ```php withPsr7Request($this->getPsr7Request()) ->withMethod('GET') ->withPath('/sample/ping') ->expectStatus(200); $this->sendRequest($request); } } ``` -------------------------------- ### Per-Request Schema Configuration Example Source: https://github.com/byjg/byjg.github.io/blob/master/docs/php/swagger-test/trait-usage.md Shows how to set the OpenAPI schema directly on the request object, eliminating the need for a setUp method. ```php class FlexibleTest extends TestCase { use OpenApiValidation; // No setUp method needed! public function testWithInlineSchema() { $schema = Schema::fromFile('openapi.json'); $request = new ApiRequester(); $request ->withSchema($schema) // Schema on request ->withMethod('GET') ->withPath('/pet/1'); // No need to call setSchema() on test class $this->sendRequest($request); } } ``` -------------------------------- ### Interactive Session Example Source: https://github.com/byjg/byjg.github.io/blob/master/docs/php/rest-reference-architecture/reference/scriptify.md Demonstrates using preloaded helper functions like `qq` for quick SQL queries and interacting with project classes within the interactive terminal. ```php # Use preloaded database executor php> qq("SELECT * FROM sample LIMIT 3") array(3) { ... } # Access your models and services php> use RestReferenceArchitecture\Model\Sample; php> $sample = new Sample(); php> $sample->setName("Test"); php> $sample->getName() 'Test' # Use helper functions php> dump($sample) ``` -------------------------------- ### Check Property Accessibility with Reflection Source: https://github.com/byjg/byjg.github.io/blob/master/docs/php/serializer/troubleshooting.md Use ReflectionClass to list public methods and verify that getter methods (starting with 'get') exist for properties. ```php // Verify getter methods exist $reflection = new ReflectionClass($user); $methods = $reflection->getMethods(ReflectionMethod::IS_PUBLIC); foreach ($methods as $method) { if (str_starts_with($method->getName(), 'get')) { echo $method->getName() . "\n"; } } ``` -------------------------------- ### Preload Commands from File Source: https://github.com/byjg/byjg.github.io/blob/master/docs/php/scriptify/terminal.md Start the terminal and preload commands from a specified PHP file. This allows for automatic setup of imports, variables, and functions. ```bash scriptify terminal --preload .scriptify-preload.php ``` ```bash scriptify terminal -p .scriptify-preload.php ``` -------------------------------- ### Run Method to Send Welcome Email Source: https://github.com/byjg/byjg.github.io/blob/master/docs/php/rest-reference-architecture/reference/scriptify.md Example of running a method to send a welcome email with user details. ```bash scriptify run \"\RestReferenceArchitecture\Service\MailService::sendWelcomeEmail\" \ --arg \"user@example.com\" --arg \"John Doe\" ``` -------------------------------- ### Environment Inheritance Setup Source: https://github.com/byjg/byjg.github.io/blob/master/docs/php/config/setup.md Demonstrates how to set up environment inheritance, allowing one environment to inherit configurations from another. The fluent API is recommended for this. ```php inheritFrom($dev); ``` -------------------------------- ### PHP Built-in Server Command Source: https://github.com/byjg/byjg.github.io/blob/master/docs/js/jquery-sse/examples.md Starts a local PHP development server on localhost at port 8080. This is an alternative to using Docker for running the examples. ```bash php -S localhost:8080 ``` -------------------------------- ### Example Workflow Update and Deployment Cycle Source: https://github.com/byjg/byjg.github.io/blob/master/docs/devops/n8n-gitops/README.md A step-by-step example of exporting, editing a script, validating changes, committing to Git, and deploying the updated workflow. ```bash # 1. Export from n8n n8n-gitops export # 2. Edit scripts vim n8n/scripts/payment-processing/validate.py # 3. Validate changes n8n-gitops validate --strict # 4. Commit to Git git add . git commit -m "Improve payment validation" git tag v1.1.0 # 5. Deploy n8n-gitops deploy --git-ref v1.1.0 ``` -------------------------------- ### Initialize and Run Migrations in PHP Source: https://github.com/byjg/byjg.github.io/blob/master/docs/php/migration/getting-started.md This PHP code demonstrates how to set up a database connection, register the database handler, create a migration instance, and execute migrations. It also shows how to add a progress callback for real-time feedback. ```php addCallbackProgress(function ($action, $currentVersion, $fileInfo) { echo "$action, $currentVersion, ${fileInfo['description']}\n"; }); // Create version table (first time only) $migration->createVersion(); // Run migrations $migration->update(); ``` -------------------------------- ### Complete Calculator Service Example Source: https://github.com/byjg/byjg.github.io/blob/master/docs/php/soap-server/programmatic-configuration.md A full example demonstrating programmatic configuration of multiple SOAP operations (add, subtract, greet) and handling requests. ```php description = 'Adds two numbers together'; $addOperation->args = [ new SoapParameterConfig('a', SoapType::Integer, 1, 1), new SoapParameterConfig('b', SoapType::Integer, 1, 1) ]; $addOperation->returnType = SoapType::Integer; $addOperation->executor = function(array $params) { return $params['a'] + $params['b']; }; // Define the subtract operation $subtractOperation = new SoapOperationConfig(); $subtractOperation->description = 'Subtracts second number from first'; $subtractOperation->args = [ new SoapParameterConfig('a', SoapType::Integer), new SoapParameterConfig('b', SoapType::Integer) ]; $subtractOperation->returnType = SoapType::Integer; $subtractOperation->executor = function(array $params) { return $params['a'] - $params['b']; }; // Define the greet operation with optional parameter $greetOperation = new SoapOperationConfig(); $greetOperation->description = 'Greets a person'; $greetOperation->args = [ new SoapParameterConfig('name', SoapType::String, 1, 1), new SoapParameterConfig('title', SoapType::String, 0, 1) // Optional ]; $greetOperation->returnType = SoapType::String; $greetOperation->executor = function(array $params) { $title = $params['title'] ?? ''; $name = $params['name']; return $title ? "$title $name" : "Hello, $name!"; }; // Create the SOAP handler $handler = new SoapHandler( soapItems: [ 'add' => $addOperation, 'subtract' => $subtractOperation, 'greet' => $greetOperation ], serviceName: 'CalculatorService', namespace: 'http://example.com/calculator', description: 'A simple calculator web service', options: ['soap_version' => SOAP_1_2] ); // Handle the request use ByJG\SoapServer\ResponseWriter; $response = $handler->handle(); ResponseWriter::output($response); ``` -------------------------------- ### Quick Start: Programmatic Configuration SOAP Service Source: https://github.com/byjg/byjg.github.io/blob/master/docs/php/soap-server/README.md Define a SOAP service using programmatic configuration. This example sets up a calculator service with an 'add' operation. ```php description = 'Adds two numbers'; $addOperation->args = [ new SoapParameterConfig('a', SoapType::Integer), new SoapParameterConfig('b', SoapType::Integer) ]; $addOperation->returnType = SoapType::Integer; $addOperation->executor = function(array $params) { return $params['a'] + $params['b']; }; $handler = new SoapHandler( soapItems: ['add' => $addOperation], serviceName: 'CalculatorService' ); $response = $handler->handle(); ResponseWriter::output($response); ```