secrethash/laravel-mixpanel

Mixpanel Bridge for Laravel

v0.1.2 2024-11-10 13:07 UTC

This package is auto-updated.

Last update: 2024-12-10 14:17:11 UTC


README

Latest Version on Packagist Tests Total Downloads

🚧 Under active development, but might be useable.

🌟 Contributions are welcomed & appreciated.

secrethash/laravel-mixpanel Banner

This package provides a sane Mixpanel PHP SDK bridge for Laravel applications.

Pre-requisites

  • Laravel: ^9.x
  • PHP: ^8.2
  • Mixpanel API Project Token

Installation

  1. Install the package via composer:

    composer require secrethash/laravel-mixpanel
  2. Publish the Migrations and Config:

    • Publish all resources [migrations, config]:

      php artisan vendor:publish --provider="Secrethash\Mixpanel\MixpanelServiceProvider"
    • Publish only migrations:

      php artisan vendor:publish --tag="laravel-mixpanel-migrations"
    • Publish only config:

      php artisan vendor:publish --tag="laravel-mixpanel-config"

Idealogies

1. Events & Listeners

We use Laravel's event and listeners to track and send data to Mixpanel. This makes it easier to hook into events as and when needed.

Although the package does not force to use events and listeners in your application while tracking, but it's still recommended for maintainability. Similarly we will also take the example of events and listeners in the examples below.

2. Events Naming Consistency

We enforce a validation to make sure all the events sent are an instance of the class set in config key laravel-mixpanel.tracker.events. This should be a string backed enum. This is done to avoid event name inconsistency on mixpanel eg: User Registered and User Created

3. User Auto-identification

Enabled by default, we try early identification of the user using a user tracker (uuid). Every user is given a unique uuid which is saved in the database column defined in the config key laravel-mixpanel.tracker.database_column.

4. Consumers Strategy

Consumer strategies are also bridged with the Mixpanel PHP SDK Consumer Strategies. Additionally, we have also added an custom consumer implementation dry which uses the custom Secrethash\Mixpanel\Consumers\DebugConsumer::class. Currently these consumers are supported:

Debugging can be enabled by setting config laravel-mixpanel.debug.enabled to true. More details in the debugging section

Usage

  1. Tracking an event is as easy as:

    use Secrethash\Mixpanel\Mixpanel;
    use Secrethash\Mixpanel\Enums\TrackingEvents;
    
    $data = [
        'registration_status' => 'success',
        'account_status' => 'verified',
    ];
    
    Mixpanel::track(TrackingEvents::userRegistered, $data);
  2. The config should to be updated to set according to the requirements. Most of the configurations can be updated from .env.

  3. A few key configurations can be set or overridden during Runtime for flexibility:

    use Secrethash\Mixpanel\Mixpanel;
    ...
    class AppServiceProvider extends ServiceProvider
    {
        ...
        public function boot()
        {
            ...
            // Enable/disable tracking for specific cases
            if (environment('testing')) {
                Mixpanel::$track = false;
            }
    
            // Add additional User Identity Attributes or Overwrite the set attributes
            Mixpanel::$identityAttr = array_merge(
                Mixpanel::$identityAttr,
                ['phone','status']
            );
    
            // Although this can be updated from the config in `laravel-mixpanel.tracker.database_column`,
            // This can be useful to override the config value if needed
            Mixpanel::$userIdentityKey = 'uuid';
        }
    }
  4. The package also provides a lot of helpful integration details in the php artisan about command:

    php artisan about
    Laravel Mixpanel Integration .................................................................  
    Active .............................................................................. INACTIVE  
    Current State ......................................... Tracking Disabled due to missing Token  
    Debugging ........................................................................... DISABLED  
    Mixpanel Consumer ..................................................................... socket  
    Mixpanel Host ........................................................................ DEFAULT  
    Mixpanel Token ......................................................................... UNSET  
    User Identity Attributes ........................................... name, last_name, username  
    User Identity Key ........................................................... mixpanel_tracker

Examples

1. Tracking an Order Successful Event

  • Order Event

    <?php
    
    namespace App\Events;
    
    use App\Models\Order;
    use Secrethash\Mixpanel\Contracts\MixpanelEvent;
    use Illuminate\Broadcasting\InteractsWithSockets;
    use Illuminate\Foundation\Events\Dispatchable;
    use Illuminate\Queue\SerializesModels;
    
    class OrderSuccessfulEvent implements MixpanelEvent
    {
        use Dispatchable, InteractsWithSockets, SerializesModels;
    
        /**
        * Create a new event instance.
        *
        * @return void
        */
        public function __construct(
            public Order $order
        ) {
        }
    }
  • Order Listener

    <?php
    
    namespace App\Listeners;
    
    use App\Enums\TrackingEvents;
    use App\Events\OrderSuccessfulEvent;
    use Secrethash\Mixpanel\Mixpanel;
    use Secrethash\Mixpanel\Listeners\BaseTrackingListener;
    
    class OrderSuccessTrackingListener extends BaseTrackingListener
    {
        /**
        * Handle the Event Listening
        *
        * @return void
        */
        public function handle(OrderSuccessfulEvent $event)
        {
            $order = $event->order;
    
            Mixpanel::track(TrackingEvents::OrderSuccessful, [
                'order_id' => $order->id,
                'seller' => [
                    'id' => $order->product->seller?->id,
                    'name' => $order->product->seller?->full_name,
                ],
                'amount' => $order->amount,
                'currency' => $order->currency,
                'status' => $order->status,
            ]);
        }
    }
  • Register the event and listener by adding the mapping to App\Providers\EventServiceProvider::$listen

    <?php
    
    namespace App\Providers;
    
    use Illuminate\Foundation\Support\Providers\EventServiceProvider;
    use App\Events\OrderSuccessfulEvent;
    use App\Listeners\OrderSuccessTrackingListener;
    
    class EventServiceProvider extends EventServiceProvider
    {
        protected $listen = [
            ...
            OrderSuccessfulEvent::class => [
                OrderSuccessTrackingListener::class,
            ],
        ];
        ...
    }

Debugging

All the debugging consumers are custom implementations to make the development process a breeze. All the above mentioned consumer strategies have custom debugging consumers implemented too.

Setting the Mixpanel in debugging mode can be done by setting the .env variable MIXPANEL_DEBUG=true. Custom Debugging Consumers can also be added and replaced directly in the config laravel-mixpanel.consumers.*.

Testing

composer test

Changelog

Please see CHANGELOG for more information on what has changed recently.

Contributing

Please see CONTRIBUTING for details.

Security Vulnerabilities

Please review our security policy on how to report security vulnerabilities.

Credits

License

The MIT License (MIT). Please see License File for more information.