定制 clinically/laravel-companion 二次开发

按需修改功能、优化性能、对接业务系统,提供一站式技术支持

邮箱:yvsm@zunyunkeji.com | QQ:316430983 | 微信:yvsm316

clinically/laravel-companion

Composer 安装命令:

composer require clinically/laravel-companion

包简介

A structured JSON API for mobile and external tooling to inspect, monitor, and manage Laravel applications.

README 文档

README

A structured JSON API for mobile and external tooling to inspect, monitor, and manage Laravel applications. Ships with an admin dashboard (Livewire + Flux) for managing authenticated agents.

Designed as the server-side companion to a native iOS app, but protocol-agnostic — any HTTP client can consume the API.

See it in action: laravel-companion-demo — a full Laravel 13 app that integrates every feature with 121 passing tests, an API Explorer, and Swagger UI docs.

Features

  • Token-based agent authentication with SHA-256 hashed tokens, scopes, expiry, IP allowlists
  • Feature toggles — enable/disable endpoint groups; disabled features have zero runtime cost
  • Model browser — introspect Eloquent models (via laravel-introspect) and browse records with filtering, sorting, pagination
  • Route inspector — list all registered routes with middleware, parameters, actions
  • Artisan command runner — execute whitelisted commands with blacklist safety net
  • Queue management — view failed jobs, retry, delete, flush
  • Cache inspector — read keys, forget keys, flush
  • Config viewer — full config tree with automatic sensitive value redaction
  • Log viewer — parsed log entries with SSE live tail streaming
  • Scheduler viewer — all scheduled commands with next due dates
  • Migration status — batched migration history
  • Event/listener map — registered events with their listeners
  • Horizon integration — status, metrics, recent jobs, pause/continue/terminate
  • Pulse integration — servers, slow queries/requests/jobs, exceptions, usage
  • Audit log — every API request logged with agent, action, payload, response code, duration
  • Admin dashboard — Livewire + Flux UI for managing agents, viewing audit logs, feature status
  • QR pairing — generate QR codes for mobile app device pairing
  • Extensible — register custom features, CompanionSerializable for model opt-in, events for integration

Requirements

For the dashboard:

Installation

composer require clinically/laravel-companion

Then run the install command:

php artisan companion:install

This publishes the config, migrations, runs migrations, and optionally creates your first agent token.

Configuration

Publish the config separately if needed:

php artisan vendor:publish --tag=companion-config

See config/companion.php for all options including:

  • Route prefix/domainCOMPANION_PATH, COMPANION_DOMAIN
  • Feature toggles — enable/disable each endpoint group
  • Scopes & presets — define what agents can access
  • Command whitelist/blacklist — control which artisan commands are executable
  • Model browser settings — hidden columns, redaction patterns, pagination, column validation
  • Cache browsercache.allowed_prefixes to restrict which keys are accessible (empty = all)
  • Config redaction — patterns, always/never redact rules
  • Rate limiting — per-agent API and SSE connection limits
  • Audit log — retention, read/write logging, automatic payload sanitisation

Artisan Commands

Command Purpose
companion:install One-time setup: publish config, run migrations, create first agent
companion:agent Create a new agent token interactively
companion:pair {agent} Display pairing info for an existing agent
companion:agents List all agents with status
companion:revoke {agent} Revoke an agent token
companion:prune-audit Prune old audit log entries
companion:status Health check and feature status overview

Dashboard

The admin dashboard is available at /{path}/dashboard (default: /companion/dashboard).

Access is controlled by the viewCompanion gate — open in local environment, locked in production. Define it in your AppServiceProvider:

Gate::define('viewCompanion', function (User $user) {
    return $user->is_admin;
});

Embeddable Livewire Components

All dashboard components can be embedded in your own admin panel:

<livewire:companion-agent-list />
<livewire:companion-agent-creator />
<livewire:companion-agent-detail :agent="$agent" />
<livewire:companion-qr-code :agent="$agent" :token="$token" />
<livewire:companion-audit-log />
<livewire:companion-scope-picker wire:model="scopes" />
<livewire:companion-feature-status />

API Authentication

Agents authenticate via bearer token:

Authorization: Bearer cmp_01hx...|a3f8b2...

Tokens are SHA-256 hashed before storage. The plain token is shown once at creation. The authenticated agent is accessible via $request->companionAgent().

HasCompanionAccess Trait

Add to your User model for convenience helpers:

use Clinically\Companion\Traits\HasCompanionAccess;

class User extends Authenticatable
{
    use HasCompanionAccess;
}

Provides $user->companionAgents(), $user->createCompanionAgent(), $user->revokeCompanionAgent(), $user->canAccessCompanion().

Custom Features

Register additional feature groups:

Companion::registerFeature('custom-metrics', function (Router $router) {
    $router->get('/custom-metrics', CustomMetricsController::class)
        ->middleware('companion.scope:custom-metrics:read');
});

Model Browser Opt-in

Implement CompanionSerializable to control exactly what's exposed:

use Clinically\Companion\Contracts\CompanionSerializable;

class Patient extends Model implements CompanionSerializable
{
    public function toCompanionArray(): array
    {
        return $this->only(['id', 'first_name', 'last_name', 'mrn']);
    }

    public function companionRelationships(): array
    {
        return ['appointments'];
    }

    public function companionScopes(): array
    {
        return ['active'];
    }
}

Events

Event When
AgentCreated New agent token generated
AgentRevoked Agent revoked
AgentAuthenticated Successful API auth
AgentAuthFailed Failed auth attempt
CommandExecuted Artisan command run via API
MutatingAction Any write operation

Security

Model Browser

  • Only models discovered in configured models.paths are accessible — arbitrary class names are rejected
  • Sort/filter column names are validated against the database schema, excluding hidden and redacted columns
  • LIKE search wildcards are escaped to prevent pattern injection
  • Scopes can only be applied to models implementing CompanionSerializable
  • Relationship data passes through the same redaction pipeline as top-level records
  • Per-page limits are enforced (min 1, max configurable)

Cache Browser

Configure companion.cache.allowed_prefixes to restrict key access:

'cache' => [
    'allowed_prefixes' => ['app:', 'companion:'],
],

When empty (default), all keys are accessible. In production, restrict to prevent exposure of session/token data.

HTTPS

HTTPS is enforced in all non-local/testing environments. Requests over plain HTTP receive a 403.

Testing

The package provides test helpers:

use Clinically\Companion\Testing\CompanionTestHelpers;

class MyTest extends TestCase
{
    use CompanionTestHelpers;

    public function test_something()
    {
        $agent = $this->createTestAgent(scopes: ['models:read']);

        $response = $this->withCompanionAgent($agent)
            ->getJson('/companion/api/models');

        $response->assertOk();
    }
}

Running Package Tests

composer test      # Pest tests
composer analyse   # PHPStan level 6
composer format    # Pint formatting

License

MIT

clinically/laravel-companion 适用场景与选型建议

clinically/laravel-companion 是一款 基于 PHP 开发的 Composer 扩展包,目前已累计 15 次下载、GitHub Stars 达 0, 最近一次更新时间为 2026 年 03 月 30 日, 在 PHP 生态内属于活跃度较高的组件。

它主要适用于以下技术方向: 「admin」 「api」 「monitoring」 「laravel」 「introspection」 「companion」 等业务场景。在实际项目中,围绕这些方向常见需要落地的问题包括:接口对接、性能调优、并发安全、与既有框架(Laravel / ThinkPHP / Yii / Webman 等)的兼容适配,以及生产环境的日志埋点与稳定性保障。

我们在过去多个企业项目中使用过 clinically/laravel-companion 或与其功能相近的方案,如果你在选型或落地过程中遇到问题,例如 版本兼容、二次改造、私有化封装、与内部系统对接、生产 BUG 排查,欢迎联系我们协助评估。

围绕 clinically/laravel-companion 我们能提供哪些服务?
定制开发 / 二次开发

基于 clinically/laravel-companion 在你已有业务上做功能扩展、字段裁剪、UI 适配、与内部账号 / 权限 / 日志系统的深度对接。

BUG 修复 & 性能优化

线上偶发问题、内存泄漏、慢查询、并发异常等排查修复;针对高流量场景做缓存、队列、索引层面的调优。

项目外包 & 长期维护

承接完整的项目从需求 → 设计 → 开发 → 上线 → 长期运维;也可按月提供技术保姆服务。

yvsm@zunyunkeji.com QQ:316430983 微信:yvsm316 西安尊云信息科技 · 专注 PHP / Go / 分布式系统研发

统计信息

  • 总下载量: 15
  • 月度下载量: 0
  • 日度下载量: 0
  • 收藏数: 0
  • 点击次数: 30
  • 依赖项目数: 0
  • 推荐数: 0

GitHub 信息

  • Stars: 0
  • Watchers: 0
  • Forks: 0
  • 开发语言: PHP

其他信息

  • 授权协议: MIT
  • 更新时间: 2026-03-30