PHPackages                             onelaravel/core - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. [Framework](/categories/framework)
4. /
5. onelaravel/core

ActiveLibrary[Framework](/categories/framework)

onelaravel/core
===============

One - Laravel Core Library for rapid development and security

018PHP

Since Mar 7Pushed 2mo agoCompare

[ Source](https://github.com/onelaravel/core)[ Packagist](https://packagist.org/packages/onelaravel/core)[ RSS](/packages/onelaravel-core/feed)WikiDiscussions main Synced 1mo ago

READMEChangelogDependenciesVersions (1)Used By (0)

One Core
========

[](#one-core)

[![PHP Version](https://camo.githubusercontent.com/7535257ca228724c93658bd52583d4e47a9bab02c356abf6e54c1d575f2151e6/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f5048502d382e312532422d626c75652e737667)](https://php.net)[![Laravel Version](https://camo.githubusercontent.com/61230a06dcc2975712e8ecc56081fc6254d98a6b371613c8e7cad258d70a92b3/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f4c61726176656c2d31312e7825323025374325323031322e782d677265656e2e737667)](https://laravel.com)[![Laravel Octane](https://camo.githubusercontent.com/5b49255e2e26202d423d1bbf671d30391ee9d30695afb317cf969f27e2bcf40e/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f4f6374616e652d322e782d6f72616e67652e737667)](https://laravel.com/docs/octane)[![License](https://camo.githubusercontent.com/fdf2982b9f5d7489dcf44570e714e3a15fce6253e0cc6b5aa61a075aac2ff71b/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f4c6963656e73652d4d49542d79656c6c6f772e737667)](LICENSE)

**One Core** - Thư viện Laravel Core cho phát triển nhanh và bảo mật, được thiết kế để tương thích hoàn toàn với Laravel 11, Laravel 12 và Laravel Octane.

🚀 Tính năng chính
-----------------

[](#-tính-năng-chính)

### 🔧 Core Engines

[](#-core-engines)

- **ShortCode Engine**: Hệ thống shortcode mạnh mẽ tương tự WordPress
- **View Manager**: Quản lý view và template với cache thông minh
- **Cache Engine**: Hệ thống cache đa lớp với auto-invalidation
- **DCrypt Engine**: Mã hóa/giải mã dữ liệu an toàn
- **JSON Data Engine**: Xử lý dữ liệu JSON hiệu quả

### 🎯 Magic Classes

[](#-magic-classes)

- **Arr**: Array wrapper với magic methods và helper functions
- **Str**: String utilities với hỗ trợ tiếng Việt
- **Any**: Universal data wrapper cho mọi kiểu dữ liệu

### 🗂️ File Management

[](#️-file-management)

- **Filemanager**: Quản lý file và thư mục toàn diện
- **File Methods**: Các phương thức xử lý file nâng cao
- **Zip Methods**: Nén và giải nén file
- **File Converter**: Chuyển đổi định dạng file

### 🌐 HTTP &amp; API

[](#-http--api)

- **HTTP Client**: HTTP client với Promise support
- **CURL Wrapper**: CURL utilities nâng cao
- **Base API**: Framework cho API development
- **HTTP Promise**: Promise-based HTTP requests

### 🎨 HTML &amp; UI

[](#-html--ui)

- **HTML Builder**: Tạo HTML elements programmatically
- **Form Builder**: Form generation với validation
- **Menu Builder**: Menu system linh hoạt
- **Input Types**: Input components đa dạng

### 📊 Repository Pattern

[](#-repository-pattern)

- **Base Repository**: Repository pattern implementation
- **CRUD Actions**: CRUD operations tự động
- **Filter Actions**: Advanced filtering và searching
- **Cache Tasks**: Cache management cho repositories
- **RepositoryTap**: Safe repository operations với error handling

### 🎨 Service Layer

[](#-service-layer)

- **ModuleService**: Service cho modules với CRUD operations
- **ViewService**: Service cho view rendering với ViewContextManager
- **ResponseMethods**: Tự động trả về View/JSON dựa trên headers
- **ViewMethods**: View rendering với context management
- **ModuleMethods**: Repository operations với error handling
- **CRUDMethods**: CRUD operations với validation

### 🔐 Security &amp; Validation

[](#-security--validation)

- **Validators**: Validation system mở rộng
- **Default Methods**: Security utilities
- **System Mail Alert**: Email security alerts

### 🎯 Event System

[](#-event-system)

- **EventMethods**: Hệ thống quản lý sự kiện mạnh mẽ
- **Event Dispatcher**: Event dispatching và handling
- **Event Methods**: Magic methods cho event management
- **Multi-listener Support**: Một event có thể có nhiều listeners
- **Class-based Isolation**: Mỗi class có vùng events riêng biệt

### 🌍 Internationalization

[](#-internationalization)

- **Locale Management**: Multi-language support
- **Language Files**: Dynamic language loading

📋 Yêu cầu hệ thống
------------------

[](#-yêu-cầu-hệ-thống)

- **PHP**: ^8.1
- **Laravel**: ^11.0 | ^12.0
- **Laravel Octane**: ^2.0 (tùy chọn)

🛠️ Cài đặt
----------

[](#️-cài-đặt)

### 1. Cài đặt qua Composer

[](#1-cài-đặt-qua-composer)

```
composer require one/core
```

### 2. Đăng ký Service Provider

[](#2-đăng-ký-service-provider)

Service Provider sẽ được tự động đăng ký thông qua Laravel's auto-discovery.

### 3. Publish Configuration và Migrations (tùy chọn)

[](#3-publish-configuration-và-migrations-tùy-chọn)

```
# Publish config file
php artisan vendor:publish --provider="One\Core\Providers\OneServiceProvider" --tag="one-config"

# Publish migrations
php artisan vendor:publish --provider="One\Core\Providers\OneServiceProvider" --tag="one-migrations"

# Hoặc publish tất cả
php artisan vendor:publish --provider="One\Core\Providers\OneServiceProvider"
```

### 4. Chạy Migrations

[](#4-chạy-migrations)

```
# Chạy migrations của thư viện
php artisan migrate

# Hoặc sử dụng command riêng
php artisan one:publish-migrations
php artisan migrate
```

🚀 Sử dụng nhanh
---------------

[](#-sử-dụng-nhanh)

### ShortCode Engine

[](#shortcode-engine)

```
use One\Core\Engines\ShortCode;

// Đăng ký shortcode
ShortCode::addShortcode('hello', function($atts, $content, $tag) {
    return 'Xin chào từ shortcode!';
});

// Sử dụng trong nội dung
$content = "Đây là nội dung. [hello] Và đây là nội dung sau.";
$result = ShortCode::do($content, false);
```

### Magic Array

[](#magic-array)

```
use One\Core\Magic\Arr;

$data = new Arr(['name' => 'John', 'age' => 30]);

// Magic methods
echo $data->name; // John
echo $data->get('age'); // 30
echo $data->has('email'); // false

// Array operations
$data->set('email', 'john@example.com');
$data->remove('age');
```

### File Management

[](#file-management)

```
use One\Core\Files\Filemanager;

$fm = new Filemanager('/path/to/directory');

// File operations
$fm->saveHtml('index.html', 'Hello World');
$content = $fm->getHtml('index.html');

// Directory operations
$files = $fm->getList();
$fm->copy('source.txt', 'destination.txt');
```

### HTTP Client

[](#http-client)

```
use One\Core\Http\Client;

$client = new Client();

// GET request
$response = $client->get('https://api.example.com/users');

// POST request với data
$response = $client->post('https://api.example.com/users', [
    'name' => 'John Doe',
    'email' => 'john@example.com'
]);
```

### Repository Pattern

[](#repository-pattern)

```
use One\Core\Repositories\BaseRepository;

class UserRepository extends BaseRepository
{
    protected $model = User::class;

    public function findByEmail($email)
    {
        return $this->model::where('email', $email)->first();
    }
}
```

### Service Layer với Auto View/JSON Response

[](#service-layer-với-auto-viewjson-response)

```
use One\Core\Services\ModuleService;
use One\Core\Support\Methods\ViewMethods;
use One\Core\Support\Methods\ResponseMethods;
use Illuminate\Http\Request;

class UserService extends ModuleService
{
    use ViewMethods, ResponseMethods;

    protected $context = 'web';
    protected $module = 'users';

    public function initUser()
    {
        $this->setRepositoryClass(UserRepository::class);
        $this->initView();
    }

    public function getUserList(Request $request)
    {
        $users = $this->repository->getResults($request);

        // Tự động trả về view hoặc JSON dựa trên header
        return $this->response($request, [
            'users' => $users,
            'title' => 'Danh sách người dùng'
        ], 'users.index');
    }
}
```

**Request Headers:**

- `x-one-response: json` → Trả về JSON
- `Accept: application/json` → Trả về JSON
- Không có header → Trả về View

### Event System

[](#event-system)

```
use One\Core\Events\EventMethods;

class UserService
{
    use EventMethods;

    public function createUser($data)
    {
        // Đăng ký event listeners
        static::on('user.creating', function($userData) {
            // Validate trước khi tạo
            return $userData;
        });

        static::on('user.created', function($user) {
            // Gửi email chào mừng
            Mail::to($user->email)->send(new WelcomeMail($user));
        });

        // Kích hoạt event trước khi tạo
        $data = static::trigger('user.creating', $data);

        $user = User::create($data);

        // Kích hoạt event sau khi tạo
        static::trigger('user.created', $user);

        return $user;
    }
}

// Sử dụng từ bên ngoài
UserService::on('user.created', function($user) {
    // Log activity
    Activity::log('user_created', $user);
});

// Kiểm tra event có tồn tại
if (UserService::hasEvent('user.created')) {
    // Event đã được đăng ký
}

### Event System - Chi tiết kỹ thuật

EventMethods trait cung cấp hệ thống quản lý sự kiện hoàn chỉnh với các tính năng:

#### **Cấu trúc dữ liệu**
- **Class-based Isolation**: Mỗi class có vùng events riêng biệt
- **Multi-listener Support**: Một event có thể có nhiều listeners
- **Case-insensitive**: Event names tự động chuyển về lowercase

#### **Các phương thức chính**
- `_addEventListener()`: Đăng ký listener cho event
- `_dispatchEvent()`: Kích hoạt event và thực thi listeners
- `_removeEvent()`: Xóa event listeners
- `_eventExists()`: Kiểm tra event có tồn tại
- `callEventMethod()`: Router chính để gọi các method

#### **Magic Methods Support**
Trait được thiết kế để hoạt động với magic methods:
- `__callStatic()`: Xử lý static method calls
- `__call()`: Xử lý instance method calls

#### **Return Values**
- `_dispatchEvent()` trả về mảng kết quả từ tất cả listeners
- Các method khác trả về boolean hoặc void tùy theo chức năng

#### **Ví dụ sử dụng thực tế**

```php
class OrderService
{
    use EventMethods;

    public function processOrder($orderData)
    {
        // Đăng ký các event listeners
        static::on('order.validating', function($data) {
            // Validate order data
            if (empty($data['items'])) {
                throw new Exception('Order must have items');
            }
            return $data;
        });

        static::on('order.processing', function($order) {
            // Update inventory
            foreach ($order->items as $item) {
                Inventory::decrease($item->product_id, $item->quantity);
            }
        });

        static::on('order.completed', function($order) {
            // Send confirmation email
            Mail::to($order->customer_email)->send(new OrderConfirmation($order));

            // Log activity
            Activity::log('order_completed', $order);
        });

        // Kích hoạt validation event
        $orderData = static::trigger('order.validating', $orderData);

        // Tạo order
        $order = Order::create($orderData);

        // Kích hoạt processing event
        static::trigger('order.processing', $order);

        // Cập nhật trạng thái
        $order->update(['status' => 'completed']);

        // Kích hoạt completion event
        static::trigger('order.completed', $order);

        return $order;
    }
}
```

🔧 Laravel Octane Support
------------------------

[](#-laravel-octane-support)

One Core được thiết kế để tương thích hoàn toàn với Laravel Octane:

### Tự động State Management

[](#tự-động-state-management)

```
use One\Core\Contracts\OctaneCompatible;

class MyService implements OctaneCompatible
{
    private static $cache = [];

    public static function resetStaticState(): void
    {
        self::$cache = [];
    }

    public function resetInstanceState(): void
    {
        // Reset instance state
    }

    public static function getStaticProperties(): array
    {
        return ['cache'];
    }
}
```

### Octane Events

[](#octane-events)

- **WorkerStarting**: Khởi tạo worker
- **RequestReceived**: Xử lý request mới
- **RequestTerminated**: Reset state sau request

📚 API Documentation
-------------------

[](#-api-documentation)

### ShortCode API

[](#shortcode-api)

MethodDescription`ShortCode::addShortcode($tag, $callback)`Đăng ký shortcode mới`ShortCode::do($content, $ignore_html)`Xử lý nội dung có shortcode`ShortCode::hasShortcode($content, $tag)`Kiểm tra shortcode có tồn tại`ShortCode::removeShortcode($tag)`Xóa shortcode### Arr API

[](#arr-api)

MethodDescription`$arr->get($key, $default)`Lấy giá trị theo key`$arr->set($key, $value)`Gán giá trị`$arr->has($key)`Kiểm tra key có tồn tại`$arr->remove($key)`Xóa key`$arr->merge($array)`Merge với array khác### Filemanager API

[](#filemanager-api)

MethodDescription`$fm->saveHtml($filename, $content)`Lưu file HTML`$fm->getHtml($filename)`Đọc file HTML`$fm->copy($src, $dst)`Copy file/thư mục`$fm->move($src, $dst)`Di chuyển file/thư mục`$fm->delete($path)`Xóa file/thư mục### Event System API

[](#event-system-api)

MethodDescription`static::on($event, $closure)`Đăng ký event listener`static::addEventListener($event, $closure)`Đăng ký event listener (alias)`static::trigger($event, ...$params)`Kích hoạt event`static::fire($event, ...$params)`Kích hoạt event (alias)`static::emit($event, ...$params)`Kích hoạt event (alias)`static::hasEvent($event)`Kiểm tra event có tồn tại`static::eventExists($event)`Kiểm tra event có tồn tại (alias)`static::hasEventListener($event)`Kiểm tra event có tồn tại (alias)`static::removeEvent($event, $closure)`Xóa event listener`static::off($event, $closure)`Xóa event listener (alias)`static::removeEventListener($event, $closure)`Xóa event listener (alias)🧪 Testing
---------

[](#-testing)

### Chạy tests

[](#chạy-tests)

```
composer test
```

### Octane Compatibility Tests

[](#octane-compatibility-tests)

```
php artisan test --filter=OctaneCompatibilityTest
```

🔒 Security
----------

[](#-security)

- Tất cả input được sanitize tự động
- SQL injection protection
- XSS protection
- CSRF protection
- Secure file operations

🌍 Internationalization
----------------------

[](#-internationalization-1)

```
use One\Core\Languages\Locale;

// Set language
Locale::setLang('vi');

// Get translation
$message = Locale::get('welcome.message');
```

📦 Package Structure
-------------------

[](#-package-structure)

```
src/
├── core/
│   ├── Async/            # Async/await utilities
│   ├── Concerns/         # Traits và shared functionality
│   ├── Contracts/        # Interfaces và contracts
│   ├── Console/          # Console commands
│   ├── Crawlers/         # Web crawling utilities
│   ├── Database/         # Database utilities
│   ├── Engines/          # Core engines (ShortCode, Cache, ViewContextManager, etc.)
│   ├── Events/           # Event system (EventMethods, EventDispatcher)
│   ├── Files/            # File management system
│   ├── Html/             # HTML builders và components
│   ├── Http/             # HTTP client và utilities
│   ├── Languages/        # Internationalization
│   ├── Laravel/          # Laravel integrations
│   ├── Magic/            # Magic classes (Arr, Str, Any)
│   ├── Mailer/           # Email system
│   ├── Masks/            # Data masking và transformation
│   ├── Models/           # Base models
│   ├── Promise/          # Promise utilities
│   ├── Providers/        # Service providers
│   ├── Queues/           # Queue management
│   ├── Repositories/     # Repository pattern implementation
│   ├── Services/         # Service classes (ModuleService, ViewService, etc.)
│   ├── Support/Methods/  # Support methods (ViewMethods, ResponseMethods, etc.)
│   ├── System/           # System utilities
│   └── Validators/       # Validation system
├── helpers/              # Helper functions
└── tests/                # Test files

```

🤝 Contributing
--------------

[](#-contributing)

1. Fork the repository
2. Create your feature branch (`git checkout -b feature/amazing-feature`)
3. Commit your changes (`git commit -m 'Add some amazing feature'`)
4. Push to the branch (`git push origin feature/amazing-feature`)
5. Open a Pull Request

📄 License
---------

[](#-license)

This project is licensed under the MIT License - see the [LICENSE](LICENSE) file for details.

📚 Documentation
---------------

[](#-documentation)

### Tài Liệu Chi Tiết

[](#tài-liệu-chi-tiết)

- **[Quick Start Guide](./docs/QUICK_START_GUIDE.md)** - Hướng dẫn bắt đầu nhanh
- **[Recent Updates Guide](./docs/RECENT_UPDATES_GUIDE.md)** - Các thay đổi gần đây
- **[Structure Overview](./docs/STRUCTURE_OVERVIEW.md)** - Tổng quan cấu trúc
- **[Response Methods Usage](./docs/RESPONSE_METHODS_USAGE.md)** - Hướng dẫn ResponseMethods
- **[View Context Manager Guide](./docs/VIEW_CONTEXT_MANAGER_GUIDE.md)** - Hướng dẫn ViewContextManager
- **[Service Architecture Analysis](./docs/SERVICE_ARCHITECTURE_ANALYSIS.md)** - Phân tích kiến trúc Service
- **[Helpers Guide](./docs/HELPERS_GUIDE.md)** - Hướng dẫn sử dụng các hàm helper

### Tài Liệu Khác

[](#tài-liệu-khác)

Xem thêm trong thư mục [`docs/`](./docs/) để biết thêm chi tiết.

🆘 Support
---------

[](#-support)

- **Documentation**:
- **Issues**: [GitHub Issues](https://github.com/one/core/issues)
- **Discussions**: [GitHub Discussions](https://github.com/one/core/discussions)
- **Email**:

🏆 Credits
---------

[](#-credits)

Developed with ❤️ by the One Team

---

**One Core** - Empowering Laravel development with powerful tools and utilities.

###  Health Score

21

—

LowBetter than 18% of packages

Maintenance57

Moderate activity, may be stable

Popularity6

Limited adoption so far

Community8

Small or concentrated contributor base

Maturity11

Early-stage or recently created project

 Bus Factor1

Top contributor holds 67.6% of commits — single point of failure

How is this calculated?**Maintenance (25%)** — Last commit recency, latest release date, and issue-to-star ratio. Uses a 2-year decay window.

**Popularity (30%)** — Total and monthly downloads, GitHub stars, and forks. Logarithmic scaling prevents top-heavy scores.

**Community (15%)** — Contributors, dependents, forks, watchers, and maintainers. Measures real ecosystem engagement.

**Maturity (30%)** — Project age, version count, PHP version support, and release stability.

### Community

Maintainers

![](https://www.gravatar.com/avatar/280ffdb28a26cb0b1c0f90a862501409b6d4bfb64652ac3235a8f321db4e3120?d=identicon)[onelaravel](/maintainers/onelaravel)

---

Top Contributors

[![gomeetech](https://avatars.githubusercontent.com/u/102217563?v=4)](https://github.com/gomeetech "gomeetech (23 commits)")[![onelaravel](https://avatars.githubusercontent.com/u/235087283?v=4)](https://github.com/onelaravel "onelaravel (11 commits)")

### Embed Badge

![Health badge](/badges/onelaravel-core/health.svg)

```
[![Health](https://phpackages.com/badges/onelaravel-core/health.svg)](https://phpackages.com/packages/onelaravel-core)
```

###  Alternatives

[laravel/passport

Laravel Passport provides OAuth2 server support to Laravel.

3.4k85.0M532](/packages/laravel-passport)[nolimits4web/swiper

Most modern mobile touch slider and framework with hardware accelerated transitions

41.8k177.2k1](/packages/nolimits4web-swiper)[laravel/dusk

Laravel Dusk provides simple end-to-end testing and browser automation.

1.9k36.7M259](/packages/laravel-dusk)[laravel/prompts

Add beautiful and user-friendly forms to your command-line applications.

712181.8M596](/packages/laravel-prompts)[cakephp/chronos

A simple API extension for DateTime.

1.4k47.7M121](/packages/cakephp-chronos)[laravel/pail

Easily delve into your Laravel application's log files directly from the command line.

91545.3M590](/packages/laravel-pail)

PHPackages © 2026

[Directory](/)[Categories](/categories)[Trending](/trending)[Changelog](/changelog)[Analyze](/analyze)
