castrocrea/mixpanel-bundle

Symfony Mixpanel 扩展包

安装: 9

依赖项: 0

建议者: 0

安全性: 0

星标: 0

关注者: 1

分支: 15

类型:symfony-bundle

3.10.0 2021-06-15 11:52 UTC

This package is auto-updated.

Last update: 2024-09-10 11:58:32 UTC


README

Build Status

Mixpanel 库集成到 Symfony。

安装

使用 Composer 安装 gordalina/mixpanel-bundle

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

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

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

config/bundles.php 中注册扩展包

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

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

# app/config/config.yml

castrocrea_mixpanel:
    projects:
        default:
            token: xxxxxxxxxxxxxxxxxxxx

使用

此扩展包注册了 castrocrea_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 Castrocrea\MixpanelBundle\Annotation as Mixpanel;

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

将人员信息发送到 Mixpanel

Mixpanel 允许您跟踪用户的行为,以及某些用户信息。当使用需要 distinct_id 的注解时,这将自动设置。只要您正确配置,就会自动执行此操作。如果您愿意,您可以覆盖此值。

# config/packages/castrocrea_mixpanel.yaml

castrocrea_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 Castrocrea\MixpanelBundle\Annotation as Mixpanel;

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

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

<?php
// OrderController.php

use Castrocrea\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 Castrocrea\MixpanelBundle\Annotation as Annotation;
use Castrocrea\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 Castrocrea\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 分析器集成

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

Example Toolbar

参考配置

下面是参考配置

# app/config/config*.yml

castrocrea_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