PHP code example of risetechapps / code-generate

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

    

risetechapps / code-generate example snippets


use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

return new class extends Migration {
    public function up(): void
    {
        Schema::create('orders', function (Blueprint $table) {
            $table->id();
            $table->codeGenerate(); // Cria campo 'code' varchar(4) unique
            $table->string('customer_name');
            $table->timestamps();
        });
    }
};



namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use RiseTechApps\CodeGenerate\Traits\HasCodeGenerate;

class Order extends Model
{
    use HasCodeGenerate;
}

// O código será gerado automaticamente: "0001", "0002", etc.
$order = Order::create(['customer_name' => 'João Silva']);
echo $order->code; // "0001"

$order2 = Order::create(['customer_name' => 'Maria Santos']);
echo $order2->code; // "0002"

class Order extends Model
{
    use HasCodeGenerate;

    protected $codeField = 'order_number';  // Campo personalizado
    protected $codeLength = 6;                // 6 dígitos
    protected $codePrefix = 'ORD-';           // Prefixo
}
// Resultado: ORD-000001, ORD-000002, ...

class Order extends Model
{
    use HasCodeGenerate;

    public function codeGenerateConfig(): array
    {
        return [
            'field' => 'order_number',
            'length' => 8,
            'prefix' => 'ORD-',
            'resetPattern' => 'Y',  // Reinicia a cada ano
            'unique' => true,
            'type' => 'string',
        ];
    }
}
// Resultado 2025: ORD-20250001, ORD-20250002
// Resultado 2026: ORD-20260001, ORD-20260002 (reiniciou)

class Order extends Model
{
    use HasCodeGenerate;

    public function codeGenerateConfigs(): array
    {
        return [
            [
                'field' => 'public_code',
                'length' => 6,
                'prefix' => 'PUB-',
            ],
            [
                'field' => 'internal_code',
                'length' => 8,
                'prefix' => 'INT-',
                'resetPattern' => 'M',  // Reinicia mensalmente
            ],
        ];
    }
}

// Migração:
Schema::create('orders', function (Blueprint $table) {
    $table->id();
    $table->codeGenerate('public_code', 10, true, 'string');
    $table->codeGenerate('internal_code', 12, true, 'string');
    $table->string('customer_name');
    $table->timestamps();
});

public function codeGenerateConfig(): array
{
    return [
        'field' => 'code',
        'length' => 10,
        'prefix' => 'ORD-',
        'resetPattern' => 'Y-m',  // Reinicia mensalmente: ORD-2025-010001
    ];
}

Schema::create('orders', function (Blueprint $table) {
    // String (padrão)
    $table->codeGenerate('code', 6, true, 'string');

    // Char
    $table->codeGenerate('short_code', 4, true, 'char');

    // Integer (apenas prefixos numéricos!)
    $table->codeGenerate('numeric_id', null, true, 'integer');

    // Big Integer
    $table->codeGenerate('big_id', null, true, 'bigint');

    // Múltiplas colunas de uma vez
    $table->codeGenerates([
        ['column' => 'code1', 'length' => 6, 'unique' => true],
        ['column' => 'code2', 'length' => 8, 'unique' => false],
    ]);
});

use RiseTechApps\CodeGenerate\Facades\CodeGenerate;

// Limpar cache de uma tabela específica
CodeGenerate::clearSchemaCache('orders', 'code');

// Limpar todo o cache
CodeGenerate::clearAllCache();

$order = Order::first();

// Atualizar código manualmente
$order->updateCode('order_number', 'NOVO-9999');

// Regenerar todos os códigos
$order->regenerateCodes();

// Verificar configuração
$config = $order->getCodeConfig('order_number');
echo $config->prefix;  // "ORD-"

use RiseTechApps\CodeGenerate\CodeGenerate;
use RiseTechApps\CodeGenerate\DTO\CodeConfig;

// Gerar código manualmente com configuração específica
$config = new CodeConfig(
    field: 'custom_code',
    length: 8,
    prefix: 'CUST-',
);

$result = CodeGenerate::generate(Order::class, $config);
echo $result->code;      // CUST-00000001
echo $result->field;     // custom_code
echo $result->success;   // true

$order = Order::first();
$order->code = 'HACKED';
$order->save();

echo $order->fresh()->code;  // Código original preservado!

// Para todas as operações
Order::ignoreCodeGenerateUpdating(true);
$order->update(['code' => 'NOVO-9999']);
Order::ignoreCodeGenerateUpdating(false);

return [
    // Cache de schema
    'cache_schema' => true,
    'cache_store' => 'redis',
    'cache_ttl' => 3600,

    // Comportamento em erro
    'throw_on_error' => true,

    // Padrões
    'default_length' => 4,
    'default_field' => 'code',
    'default_prefix' => '',

    // Concorrência
    'max_collision_attempts' => 5,
];

class Order extends Model
{
    use HasCodeGenerate;

    public function codeGenerateConfig(): array
    {
        return [
            'field' => 'order_number',
            'length' => 10,
            'prefix' => 'PED-',
            'resetPattern' => 'Y',
        ];
    }
}

// PED-20250001, PED-20250002...
// Em 2026: PED-20260001, PED-20260002... (reiniciou)

class Protocol extends Model
{
    use HasCodeGenerate;

    public function codeGenerateConfig(): array
    {
        return [
            'field' => 'protocol_number',
            'length' => 12,
            'prefix' => 'PROT-',
            'resetPattern' => 'm',  // 202501, 202502...
        ];
    }
}

// PROT-2025010001, PROT-2025010002...
// Em fevereiro: PROT-2025020001... (reiniciou)

class Customer extends Model
{
    use HasCodeGenerate;

    public function codeGenerateConfigs(): array
    {
        return [
            [
                'field' => 'public_id',
                'length' => 6,
                'prefix' => 'CLI-',
            ],
            [
                'field' => 'internal_id',
                'length' => 10,
                'prefix' => 'INT-C-',
                'resetPattern' => null,  // Sequência contínua
            ],
        ];
    }
}
bash
php artisan vendor:publish --tag=code-generate-config