gordalina/mixpanel-bundle

Mixpanel 的 Symfony 扩展包

安装次数: 142,211

依赖者: 0

建议者: 0

安全性: 0

星级: 14

关注者: 5

分支: 15

公开问题: 2

类型:symfony-bundle

5.1.0 2024-07-29 18:03 UTC

This package is auto-updated.

Last update: 2024-08-29 18:13:03 UTC


README

Build Status

Mixpanel 库集成到 Symfony。

安装

使用 composer 安装 gordalina/mixpanel-bundle

$ php composer.phar require gordalina/mixpanel-bundle:~5.0

或在 composer.json 文件中添加 gordalina/mixpanel-bundle

{
    "require": {
        "gordalina/mixpanel-bundle": "~5.0"
    }
}

config/bundles.php 中注册扩展包

// config/bundles.php
    return [
        // ...
        Gordalina\MixpanelBundle\GordalinaMixpanelBundle::class => ['all' => true],
    ];
}

app/config/config.yml 中启用扩展包配置

# app/config/config.yml

gordalina_mixpanel:
    projects:
        default:
            token: xxxxxxxxxxxxxxxxxxxx

使用

此扩展包注册了 gordalina_mixpanel.defaultmixpanel.defaultmixpanel 服务,这是一个来自官方库的 Mixpanel 实例。您可以使用它做任何事情。

注意: 此扩展包会自动发送您的客户端 IP 地址。如果您在服务器上使用反向代理,应在您的入口控制器 public/index.php 中设置它

// public/index.php
Request::setTrustedProxies(
    // the IP address (or range) of your proxy
    ['192.0.0.1', '10.0.0.0/8'],
    Request::HEADER_X_FORWARDED_ALL
);

您可以在 Symfony 网站上找到更多文档:如何配置 Symfony 在负载均衡器或反向代理后面工作

杀手特性

使用单个注解跟踪事件

<?php
// CheckoutController.php

use Gordalina\MixpanelBundle\Annotation as Mixpanel;

class CheckoutController
{
    /**
     * @Mixpanel\Track("View Checkout")
     */
    public function view(Request $request)
    {
        // ...
    }

将人员信息发送到 Mixpanel

Mixpanel 允许您跟踪您用户的行为,以及一些用户信息。当使用需要 distinct_id 的注解时,这将被自动设置。只要您正确配置,就会自动完成此操作。您可以选择覆盖此值。

# config/packages/gordalina_mixpanel.yaml

gordalina_mixpanel:
    projects:
        default:
            token: xxxxxxxxxx
    users:
        Symfony\Component\Security\Core\User\UserInterface:
            id: username
            $email: email

        # All possible properties
        YourAppBundle\Entity\User:
            id: id
            $first_name: first_name
            $last_name: last_name
            $email: email
            $phone: phone
            extra_data:
                - { key: whatever, value: test }

此扩展包使用属性访问从用户对象中获取值,因此即使您没有 first_name 属性,但有 getFirstName 方法,它也会工作。

注意: extra_data 对应 Mixpanel 用户配置文件中的非默认属性

<?php
// UserController.php

use Gordalina\MixpanelBundle\Annotation as Mixpanel;

class UserController
{
    /**
     * @Mixpanel\UpdateUser()
     */
    public function userUpdated(User $user, Request $request)
    {
        // ...
    }

在以下示例中,我们调用 UpdateUser,它发送上述配置中注册的所有信息,但我们使用一个评估用户 ID 的表达式覆盖了 id 属性。此 @Expression 注解使用 ExpressionLanguage 进行评估。

<?php
// OrderController.php

use Gordalina\MixpanelBundle\Annotation as Mixpanel;

class OrderController
{
    /**
     * @Mixpanel\Track("Order Completed", props={
     *      "user_id": @Mixpanel\Expression("user.getId()")
     * })
     * @Mixpanel\TrackCharge(
     *      id=324"),
     *      amount=@Mixpanel\Expression("order.getAmount()")
     * )
     */
    public function orderCompleted(Order $order, Request $request)
    {
        // ...
    }

注解

Mixpanel 动作

事件

  • @Mixpanel\Register(prop="visits", value=3)
  • @Mixpanel\Track(event="name", props={ "firstTime": true })
  • @Mixpanel\Unregister(prop="$email")

参与度

  • @Mixpanel\Append(id=324, prop="fruits", value="apples" [, ignoreTime=false])
  • @Mixpanel\ClearCharges(id=324 [, ignoreTime=false])
  • @Mixpanel\DeleteUser(id=324 [, ignoreTime=false])
  • @Mixpanel\Increment(id=324, prop="visits", value=3 [, ignoreTime=false])
  • @Mixpanel\Remove(id=324, prop="$email")
  • @Mixpanel\Set(id=324, props={ "firstTime": true } [, ignoreTime=false])
  • @Mixpanel\SetOnce(id=324, props={ "firstTime": true } [, ignoreTime=false])
  • @Mixpanel\TrackCharge(id=697, amount="20.0" [, ignoreTime=false])

自定义注解

  • @Mixpanel\Id()
  • @Mixpanel\Expression(expression="<expression>")
  • @Mixpanel\UpdateUser()

注意:第一个参数不需要显式指定名称,例如:@Mixpanel\Expression("<expression>")@Mixpanel\Set("<property>", value="<value>")

注意:所有 id 属性都可以省略,因为它们会使用 security.context 中的当前用户 ID 来设置。

根据条件发送事件

在所有注解中,您可以使用 表达式语言 添加条件。

/**
* @Mixpanel\Track("Your event", condition="request.getMethod() in ['GET']")
*/
public function yourAction()
{
  // ...
}

注意:默认情况下条件为真,不需要指定。

MixpanelEvent

如果注解不够用,您还可以通过 symfony 事件发送事件,如下所示

#In controller
namespace myNamespace;

use Gordalina\MixpanelBundle\Annotation as Annotation;
use Gordalina\MixpanelBundle\Mixpanel\Event\MixpanelEvent;
use Symfony\Component\EventDispatcher\EventDispatcherInterface;

// ...

public function edit(User $user, EventDispatcherInterface $eventDispatcher, Request $request)
{
    // Your code
    $annotation = new Annotation\Track();
    $annotation->event = 'My event';
    $annotation->props = [
        'prop 1' => 'data 1',
        'prop 2' => 'data 2',
    ];

    $eventDispatcher->dispatch(new MixpanelEvent($annotation, $request));
    // Rest of your code
}

覆盖所有注解中的 Props

在您的所有注解中,可以有这样的内容

    /**
     * @Mixpanel\Track("Your event", props={
     *      "user_id": @Mixpanel\Expression("user.getId()")
     * })
     */
    public function yourAction()
    {
        // ...
    }

总是需要在注解中放置相同的属性可能会很烦人。事件的运行机制允许我们避免这种情况。

namespace YourNamespace;

use Doctrine\Common\Annotations\Reader;
use Gordalina\MixpanelBundle\Annotation;
use Symfony\Component\HttpKernel\Event\ControllerEvent;
use Symfony\Component\Security\Core\Security;

class MixpanelListener
{
    private $annotationReader;
    private $security;

    public function __construct(Reader $annotationReader, Security $security)
    {
        $this->annotationReader = $annotationReader;
        $this->security         = $security;
    }

    public function onKernelController(ControllerEvent $event)
    {
        if (!\is_array($controller = $event->getController())) {
            return;
        }

        $className = \get_class($controller[0]);
        $object    = new \ReflectionClass($className);
        $method    = $object->getMethod($controller[1]);

        $classAnnotations  = $this->annotationReader->getClassAnnotations($object);
        $methodAnnotations = $this->annotationReader->getMethodAnnotations($method);

        foreach ([$classAnnotations, $methodAnnotations] as $collection) {
            foreach ($collection as $annotation) {
                if ($annotation instanceof Annotation\Annotation && property_exists($annotation, 'props')) {
                    $annotation->props['user_id'] = $this->security->getUser()->getId();
                }
            }
        }
    }
}

并在您的配置文件中

    YourNamespace\MixpanelListener:
        tags:
            - { name: kernel.event_listener, event: kernel.controller, method: onKernelController, priority: -200 }

Symfony Profiler 集成

Mixpanel 扩展包还集成了 Symfony2 性能分析器。您可以检查发送的事件和参与次数、总执行时间和其他信息。

Example Toolbar

参考配置

以下为参考配置

# app/config/config*.yml

gordalina_mixpanel:
    enabled: true                                        # defaults to true
    enable_profiler: %kernel.debug%                      # defaults to %kernel.debug%
    auto_update_user: %kernel.debug%                     # defaults to %kernel.debug%
    throw_on_user_data_attribute_failure: %kernel.debug% # defaults to %kernel.debug%
    projects:
        default:
            token: xxxxxxxxxxxxxxxxxxxxxxxxxxxx # required
            options:
                max_batch_size:  50               # the max batch size Mixpanel will accept is 50,
                max_queue_size:  1000             # the max num of items to hold in memory before flushing
                debug:           false            # enable/disable debug mode (logs messages to error_log)
                consumer:        curl             # which consumer to use (curl, file, socket)
                consumers:
                    custom_consumer:  ConsumerStrategies_CustomConsumConsumer # Your consumer, update above to use it
                host:            api.mixpanel.com # the host name for api calls
                events_endpoint: /track           # host relative endpoint for events
                people_endpoint: /engage          # host relative endpoint for people updates
                use_ssl:         true             # use ssl when available
                error_callback:  'Doctrine\Common\Util\Debug::dump'

        minimum_configuration:
            token: xxxxxxxxxxxxxxxxxxxxxxxxxxxx
    users:
        Symfony\Component\Security\Core\User\UserInterface:
            id: username
            $email: email

        # All possible properties
        YourAppBundle\Entity\User:
            id: id
            $first_name: first_name
            $last_name: last_name
            $email: email
            $phone: phone

规范

为了运行规范,请使用 composer 安装所有组件,然后运行

./bin/phpspec run

许可

此扩展包采用 MIT 许可证发布。请参阅扩展包中的完整许可证

Resources/meta/LICENSE