rconfig/laravel-zabbix
Composer 安装命令:
composer require rconfig/laravel-zabbix
包简介
Laravel-first Zabbix JSON-RPC API client with fluent, testable DX.
README 文档
README
A Laravel-first, developer-friendly client for the Zabbix JSON-RPC API that makes monitoring integrations a breeze, developed by rConfig.
✨ Features
- 🎯 Intuitive fluent API with chainable query methods ending in
.get() - 🚀 First-class developer experience with expressive, readable syntax
- ⚡ No double method calls - just chain directly:
hosts()->limit(5)->get() - 🧪 Local testing without a live Zabbix server via HTTP fakes
- 🔧 Optional real server integration for end-to-end testing
- 📦 Laravel package best practices with auto-discovery
- 🔌 Extensible design for additional Zabbix endpoints
📦 Installation
Install via Composer:
composer require rconfig/laravel-zabbix
The service provider will be auto-discovered. Optionally publish the config:
php artisan vendor:publish --tag=zabbix-config
⚙️ Configuration
Environment Variables
# Server connection ZABBIX_BASE_URL=https://zabbix.example.com ZABBIX_ENDPOINT=/api_jsonrpc.php # Authentication (use token when possible) ZABBIX_API_TOKEN=your_api_token_here # Legacy fallback ZABBIX_USERNAME=Admin ZABBIX_PASSWORD=zabbix # HTTP client settings ZABBIX_TIMEOUT=15 ZABBIX_RETRIES=2 # Testing mode ZABBIX_FAKE_BY_DEFAULT=true
Config File
The config file at config/zabbix.php provides sensible defaults:
return [ 'base_url' => env('ZABBIX_BASE_URL', 'http://localhost'), 'endpoint' => env('ZABBIX_ENDPOINT', '/api_jsonrpc.php'), // Prefer API token (Zabbix 5.4+) 'token' => env('ZABBIX_API_TOKEN'), // Legacy authentication 'username' => env('ZABBIX_USERNAME'), 'password' => env('ZABBIX_PASSWORD'), // HTTP settings 'timeout' => (int) env('ZABBIX_TIMEOUT', 15), 'retries' => (int) env('ZABBIX_RETRIES', 2), 'retry_sleep_ms' => (int) env('ZABBIX_RETRY_SLEEP_MS', 250), // Testing 'fake_by_default' => env('ZABBIX_FAKE_BY_DEFAULT', true), ];
🚀 Quick Start
use Rconfig\Zabbix\Exceptions\UnsupportedOperationException; // Connect with credentials $zabbix = ZabbixApi::login('https://zabbix.example.com', 'Admin', 'zabbix'); // Or use API token (recommended) $zabbix = ZabbixApi::login('https://zabbix.example.com', null, null, [ 'token' => 'your_api_token_here' ]); // Get API version $version = $zabbix->apiVersion(); // "7.0.0" // List all hosts $hosts = $zabbix->hosts()->all(); // Find active Linux servers with fluent syntax $activeLinux = $zabbix->hosts() ->where(['status' => 0, 'name' => 'linux-server']) ->get(); // Create a new host $newHost = $zabbix->hosts()->create([ 'host' => 'app-01', 'interfaces' => [[ 'type' => 1, 'main' => 1, 'useip' => 1, 'ip' => '10.0.0.50', 'port' => '10050' ]], 'groups' => [['groupid' => '2']], ]);
🔍 Fluent Queries
Build complex queries with an intuitive fluent interface:
Hosts
$zabbix = ZabbixApi::login($url, null, null, ['token' => $token]); // Simple fluent API - much cleaner! $hosts = $zabbix->hosts() ->limit(50) ->select(['hostid', 'host', 'status']) ->withInterfaces() ->withGroups() ->where(['status' => 0]) ->sort('host') ->get(); // Get count of hosts $totalHosts = $zabbix->hosts()->count(); // or $totalHosts = $zabbix->hosts()->countOnly()->get();
Host Groups
$groups = $zabbix->hostGroups() ->limit(20) ->select(['groupid', 'name']) ->get();
Advanced Query Builder (Alternative)
For complex queries, you can still use the explicit query builder:
$hosts = $zabbix->hosts()->get( $zabbix->hosts()->query() ->select(['hostid', 'host', 'status']) ->withInterfaces() ->withGroups() ->where(['status' => 0]) ->limit(50) ->sort('host') );
📊 Version Matrix & Compatibility
| Zabbix Version | Tested Minor | Notes |
|---|---|---|
| 6.0 LTS | 6.0.29 | Fully supported. apiinfo.version requires auth in some setups. |
| 7.x | 7.0.2 | Fully supported. Some methods differ slightly in param requirements. |
We recommend running your integration tests against both LTS and current major to catch method or parameter changes early.
🚫 Unsupported Operations
Some Zabbix API resources do not implement all CRUD operations.
For example, certain system resources cannot be created or deleted.
In these cases:
- Methods like
create(),update(), ordelete()will throw anUnsupportedOperationException - This makes it clear the operation isn’t available for that resource, rather than failing silently.
Example:
use Rconfig\Zabbix\Exceptions\ZabbixException; try { Zabbix::apiinfo()->delete(['id' => 1]); } catch (UnsupportedOperationException $e) { echo $e->getMessage(); // "Delete is not supported for Apiinfo resource" } --- ## 🛡️ Lightweight Parameter Validation An **optional** guard can warn or throw if obviously invalid parameters are passed. This is not a full schema validator — just common-sense checks to help catch mistakes early. * Wrong data types for known fields * Mutually exclusive params used together * Missing required params for certain calls Enable warnings in `.env`: ```env ZABBIX_PARAM_VALIDATION=true
Example:
// Will trigger a warning about 'limit' being a string instead of an integer Zabbix::hosts()->get(['limit' => 'fifty']);
🔐 Authentication
API Token (Recommended)
For Zabbix 5.4+ with API tokens:
$zabbix = ZabbixApi::login('https://zabbix.example.com', null, null, [ 'token' => 'your_api_token_here' ]);
Username/Password
Legacy authentication:
$zabbix = ZabbixApi::login('https://zabbix.example.com', 'Admin', 'zabbix');
Advanced Options
SSL and timeout configuration:
$zabbix = ZabbixApi::login('https://zabbix.example.com', 'Admin', 'zabbix', [ // SSL options 'sslVerifyPeer' => false, 'sslVerifyHost' => false, // Timeout settings 'timeout' => 30, 'connectTimeout' => 10, // Debug and compression 'debug' => true, 'useGzip' => true ]);
Environment Configuration
You can still use environment variables for default values:
ZABBIX_BASE_URL=https://zabbix.example.com ZABBIX_API_TOKEN=your_api_token_here ZABBIX_USERNAME=Admin ZABBIX_PASSWORD=zabbix
Then use in your code:
$zabbix = ZabbixApi::login([ 'url' => config('zabbix.base_url'), 'token' => config('zabbix.token'), ]);
🧪 Testing
Fake Mode (Default)
Perfect for local development and unit testing - no real server needed:
// All calls return realistic mock data $zabbix = ZabbixApi::login('fake://localhost'); $hosts = $zabbix->hosts()->all(); // Returns mock data
Integration Testing
Test against a real Zabbix server:
$zabbix = ZabbixApi::login($url, null, null, ['token' => $token]);
Example Test
it('fetches hosts via fluent query', function () { $zabbix = ZabbixApi::login('fake://localhost'); $hosts = $zabbix->hosts()->all(); expect($hosts)->toBeArray()->not->toBeEmpty(); });
⚠️ Error Handling
The package provides specific exceptions for different error types:
use Rconfig\Zabbix\Exceptions\ZabbixException; use Rconfig\Zabbix\Exceptions\ZabbixHttpException; use Rconfig\Zabbix\Facades\ZabbixApi; try { $zabbix = ZabbixApi::login($url, null, null, ['token' => $token]); $hosts = $zabbix->hosts()->all(); } catch (ZabbixException $e) { // API-level errors (invalid params, auth issues, etc.) logger()->error('Zabbix API error: ' . $e->getMessage()); } catch (ZabbixHttpException $e) { // HTTP transport errors (timeouts, connectivity, etc.) logger()->error('Zabbix HTTP error: ' . $e->getMessage()); }
🛠️ Local Development
Package Development Setup
For developing this package alongside a Laravel application:
/code
├─ myapp/ # Your Laravel app
└─ rconfig-laravel-zabbix/ # This package
1. Link the Package
In your Laravel app's composer.json:
{
"repositories": [
{
"type": "path",
"url": "../rconfig-laravel-zabbix",
"options": { "symlink": true }
}
]
}
2. Install the Package
cd myapp composer require rconfig/laravel-zabbix:"dev-main" php artisan vendor:publish --tag=zabbix-config
3. Test in Tinker
php artisan tinker >>> use Rconfig\Zabbix\Facades\ZabbixApi; >>> $zabbix = ZabbixApi::login('fake://localhost'); >>> $zabbix->apiVersion() // "7.0.0" (fake) >>> $zabbix->hosts()->all() // Mock data
4. Quick Test Route
// routes/web.php Route::get('/zabbix-test', function () { $zabbix = ZabbixApi::login(['url' => 'fake://localhost']); return [ 'version' => $zabbix->apiVersion(), 'hosts' => $zabbix->hosts()->all(5), ]; });
Here’s a clean way to add it to your main README so contributors (or future you) know exactly how to cut a release. I’d suggest adding a "Releases" or "Publishing" section at the bottom:
📦 Publishing a New Release
We use Semantic Versioning for all releases.
1. Update the Changelog
- Edit
CHANGELOG.md - Add a new section at the top for the version you’re releasing:
## [0.1.0] - 2025-08-09 ### Added - Initial public release of the Laravel Zabbix client.
- Commit the changes:
git add CHANGELOG.md
git commit -m "docs: update changelog for v0.1.0"
git push origin main
2. Tag the Release
Create an annotated Git tag and push it:
git tag -a v0.1.0 -m "v0.1.0 initial public release"
git push origin v0.1.0
3. Create the GitHub Release
- Go to the GitHub Releases page.
- Click Draft a new release.
- Select the tag you just pushed (
v0.1.0). - Set the title to match the tag (e.g.
v0.1.0). - Paste the changelog notes for that version.
- Publish the release.
💡 Tip: If the Packagist webhook is active, the new version will appear there automatically within minutes.
🗺️ Roadmap
Planned features for future releases:
- Pagination Support
- More fluent convenience methods
🤝 Contributing
We welcome contributions! Here's how to get started:
Development Setup
- Fork and clone the repository
- Install dependencies:
composer install
- Run the test suite:
vendor/bin/pest
- Make your changes in a feature branch
- Submit a pull request with a clear description
Coding Standards
- Follow PSR-12 for PHP code style
- Use Pint for automatic formatting. Push to main will fail if there are formatting issues.
vendor/bin/pint
- Keep methods small and expressive
- Add tests for new features and bug fixes
- Update documentation when applicable
- Use meaningful commit messages
Running Tests
# Run all tests with fakes vendor/bin/pest # Run integration tests (requires real Zabbix server) RUN_ZABBIX_INTEGRATION=1 \ ZABBIX_BASE_URL=https://your-zabbix.com \ ZABBIX_API_TOKEN=your_token \ vendor/bin/pest
📄 License
This package is open-sourced software licensed under the MIT license.
Code of Conduct
While we aren't directly affiliated with Zabbix or Laravel, but we follow their respective Codes of Conduct. We expect you to abide by these guidelines as well.
Authors
This library is created by rConfig Developers for the Zabbix and Laravel communities.
License
The MIT License (MIT). Please see License File for more information.
Built with ❤️ by rConfig for the Zabbix and Laravel communitiesrconfig/laravel-zabbix 适用场景与选型建议
rconfig/laravel-zabbix 是一款 基于 PHP 开发的 Composer 扩展包,目前已累计 1.41k 次下载、GitHub Stars 达 0, 最近一次更新时间为 2025 年 08 月 09 日, 在 PHP 生态内属于活跃度较高的组件。
它主要适用于以下技术方向: 「api」 「client」 「fluent」 「monitoring」 「zabbix」 「laravel」 等业务场景。在实际项目中,围绕这些方向常见需要落地的问题包括:接口对接、性能调优、并发安全、与既有框架(Laravel / ThinkPHP / Yii / Webman 等)的兼容适配,以及生产环境的日志埋点与稳定性保障。
我们在过去多个企业项目中使用过 rconfig/laravel-zabbix 或与其功能相近的方案,如果你在选型或落地过程中遇到问题,例如 版本兼容、二次改造、私有化封装、与内部系统对接、生产 BUG 排查,欢迎联系我们协助评估。
基于 rconfig/laravel-zabbix 在你已有业务上做功能扩展、字段裁剪、UI 适配、与内部账号 / 权限 / 日志系统的深度对接。
线上偶发问题、内存泄漏、慢查询、并发异常等排查修复;针对高流量场景做缓存、队列、索引层面的调优。
承接完整的项目从需求 → 设计 → 开发 → 上线 → 长期运维;也可按月提供技术保姆服务。
与 rconfig/laravel-zabbix 相关的其它包
同方向 / 同关键字的高下载量 PHP Composer 包推荐,方便对比选型:
Presentation and Formatting helper with nice fluent interface.
Traits gathering fluent syntax common methods
A modern, fluent HTTP client. Forked from Mashape, reimagined by Nidux, and open-sourced for the PHP community.
A PSR-7 compatible library for making CRUD API endpoints
Mock PSR-18 HTTP client
A fluent PHP CURL wrapper
统计信息
- 总下载量: 1.41k
- 月度下载量: 0
- 日度下载量: 0
- 收藏数: 0
- 点击次数: 17
- 依赖项目数: 0
- 推荐数: 0
其他信息
- 授权协议: MIT
- 更新时间: 2025-08-09