jjzjj

php - 如何在现有的 Symfony2 应用程序中实现 Sylius OrderBundle

coder 2024-05-02 原文

我需要在我的 symfony2 应用程序中实现 syliusOrderBundle,我已经从他们的官方网站上一遍又一遍地阅读文档 http://docs.sylius.org/en/latest/bundles/SyliusOrderBundle/installation.html 我最终安装并启用了以下 bundle

      new Sylius\Bundle\ResourceBundle\SyliusResourceBundle(),
        new Sylius\Bundle\MoneyBundle\SyliusMoneyBundle(),
        new Sylius\Bundle\OrderBundle\SyliusOrderBundle(),
        new Sylius\Bundle\CartBundle\SyliusCartBundle(),
        new Sylius\Bundle\ProductBundle\SyliusProductBundle(),
        new Sylius\Bundle\ArchetypeBundle\SyliusArchetypeBundle(),
        new Sylius\Bundle\AttributeBundle\SyliusAttributeBundle(),
        new Sylius\Bundle\AssociationBundle\SyliusAssociationBundle(),
        new Sylius\Bundle\VariationBundle\SyliusVariationBundle(),

问题是出于安全原因我不喜欢安装不必要的包,而且 sylius 文档也没有帮助。我所需要的只是能够将产品添加到订单中,如果您之前使用过它,请帮忙。谢谢

最佳答案

首先,您只需要 sylius/order-bundle 版本 0.17(在撰写本文时)

$ composer require sylius/order-bundle "^0.17"

然后将必要的包添加到app/AppKernel.php:

public function registerBundles()
{
    $bundles = [
        // Bundles you've already registered go here.

        // The following bundles are dependencies of Sylius ResourceBundle.
        new FOS\RestBundle\FOSRestBundle(),
        new JMS\SerializerBundle\JMSSerializerBundle($this),
        new Stof\DoctrineExtensionsBundle\StofDoctrineExtensionsBundle(),
        new WhiteOctober\PagerfantaBundle\WhiteOctoberPagerfantaBundle(),

        // The following Sylius bundles are dependencies of Sylius OrderBundle 
        new Sylius\Bundle\ResourceBundle\SyliusResourceBundle(),
        new Sylius\Bundle\MoneyBundle\SyliusMoneyBundle(),
        new Sylius\Bundle\SequenceBundle\SyliusSequenceBundle(),

        new Sylius\Bundle\OrderBundle\SyliusOrderBundle(),

        // Doctrine bundle MUST be the last bundle registered.

        new Doctrine\Bundle\DoctrineBundle\DoctrineBundle(),
    ];

    //....

    return $bundles;
}

现在要将 OrderBundle 与您自己的实体一起使用,您需要创建一个 OrderOrderItem 实体来扩展 Sylius 提供的实体。

对于 Order,我们将添加一个字段来捕获访问者的电子邮件地址。您可以捕获当前用户,或任何您喜欢的内容来确定是谁下了订单。

<?php

namespace AppBundle\Entity;

use Sylius\Component\Order\Model\Order as SyliusOrder;

class Order extends SyliusOrder
{
    /**
     * @var string
     */
    private $email;

    /**
     * @return string
     */
    public function getEmail()
    {
        return $this->email;
    }

    /**
     * @param string $email
     */
    public function setEmail($email)
    {
        $this->email = $email;
    }
}

为了演示的目的,我们假设访问者想要订购音乐轨道以供下载。

否则,这可以是任何东西。在 Sylius 应用程序中,它是一个产品。在某些应用中,它可能不是产品,而是订阅或服务等。

因此,对于 OrderItem,我们将添加一个字段来捕获访问者将订购的下载内容。

<?php

namespace AppBundle\Entity;

use Sylius\Component\Order\Model\OrderItem as SyliusOrderItem;

class OrderItem extends SyliusOrderItem
{
    /**
     * @var Download
     */
    private $download;

    /**
     * @return Download
     */
    public function getDownload()
    {
        return $this->download;
    }

    /**
     * @param Download $download
     */
    public function setDownload(Download $download)
    {
        $this->download = $download;
    }
}

现在你有了你的实体,你可以添加 Doctrine 映射。在此示例中,我们使用 XML(丑陋,但它验证配置)但它可以是 YAML 或注释。

src/AppBundle/Resources/config/doctrine/Order.orm.xml 中:

<?xml version="1.0" encoding="UTF-8"?>

<doctrine-mapping xmlns="http://doctrine-project.org/schemas/orm/doctrine-mapping"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://doctrine-project.org/schemas/orm/doctrine-mapping
        http://doctrine-project.org/schemas/orm/doctrine-mapping.xsd">

<entity name="AppBundle\Entity\Order" table="app_order">
    <field name="email" column="email" type="string" nullable="true" />

    <one-to-many field="items" target-entity="Sylius\Component\Order\Model\OrderItemInterface" mapped-by="order" orphan-removal="true">
        <cascade>
            <cascade-all/>
        </cascade>
    </one-to-many>

    <one-to-many field="adjustments" target-entity="Sylius\Component\Order\Model\AdjustmentInterface" mapped-by="order" orphan-removal="true">
        <cascade>
            <cascade-all/>
        </cascade>
    </one-to-many>
</entity>

src/AppBundle/Resources/config/doctrine/OrderItem.orm.xml 中:

<?xml version="1.0" encoding="UTF-8"?>

<doctrine-mapping xmlns="http://doctrine-project.org/schemas/orm/doctrine-mapping"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://doctrine-project.org/schemas/orm/doctrine-mapping
         http://doctrine-project.org/schemas/orm/doctrine-mapping.xsd">

    <entity name="AppBundle\Entity\OrderItem" table="app_order_item">
        <many-to-one field="download" target-entity="AppBundle\Entity\Download">
            <join-column name="download_id" referenced-column-name="id" nullable="false" />
        </many-to-one>

    </entity>

</doctrine-mapping>

然后我们需要让 Sylius OrderBundle 知道我们的新实体,这样它就不会使用它的默认实体。

我们还想为我们的 Order 实体生成订单号,这是由 Sylius SequenceBundle 完成的。

app/config/config.yml中,添加如下配置:

sylius_sequence:
    generators:
        AppBundle\Entity\Order: sylius.sequence.sequential_number_generator

sylius_order:
    resources:
        order:
            classes:
                model: AppBundle\Entity\Order
        order_item:
            classes:
                model: AppBundle\Entity\OrderItem

然后更新您的数据库模式:

$ php app/console doctrine:schema:update --dump-sql --force

现在,为了在持久化新实体时实际生成订单号并将其分配给 Order,我们需要注册一个监听器。

app/config/services.yml 或您的包的 Resources/config/services.yml 中,添加此配置:

parameters:
  sylius.model.sequence.class: Sylius\Component\Sequence\Model\Sequence

services:
  app.order_number_listener:
    class: Sylius\Bundle\OrderBundle\EventListener\OrderNumberListener
    arguments:
      - "@sylius.sequence.doctrine_number_listener"
    tags:
      - { name: kernel.event_listener, event: app.download_ordered, method: generateOrderNumber }

app.download_ordered 事件的名称在这里很重要,您可以随意命名,但必须在创建新订单时发送。

这是一个创建新订单的示例,我们在其中发送 app.download_ordered 事件。

    use AppBundle\Entity\Download;
    use AppBundle\Entity\OrderItem;
    use AppBundle\Form\OrderType;
    use Sensio\Bundle\FrameworkExtraBundle\Configuration as Framework;
    use AppBundle\Entity\Order;
    use Symfony\Bundle\FrameworkBundle\Controller\Controller;
    use Symfony\Component\EventDispatcher\GenericEvent;
    use Symfony\Component\HttpFoundation\Request;

    const STATE_BEGIN    = 'begin';
    const STATE_COMPLETE = 'complete';

    /**
     * @Framework\Route("/begin-order-for-download/{id}", name="begin_order_for_download")
     */
    public function beginOrderForDownloadAction(Request $request, $id)
    {
        $download = $this->getDoctrine()->getRepository(Download::class)->findOneBy(['id' => $id]);

        $order = new Order();
        $form = $this->createForm(new OrderType(), $order);

        if ('POST' === $request->getMethod()) {
            $order->setState(self::STATE_BEGIN);

            $orderItem = new OrderItem();
            $orderItem->setDownload($download);
            $orderItem->setOrder($order);
            $orderItem->setUnitPrice(59);
            // $orderItem->setImmutable(true); // Need to verify how this affects behavior.

            $this->get('event_dispatcher')->dispatch('app.download_ordered', new GenericEvent($order));

            $form->handleRequest($request);

            $em = $this->getDoctrine()->getManager();

            if ($form->isValid()) {
                $order->setState(self::STATE_COMPLETE);
                $this->addFlash('order.state', self::STATE_COMPLETE);

                $em->persist($order);
                $em->flush();

                return $this->redirectToRoute('complete_order', [
                    'id' => $order->getId(),
                ]);
            }
        }

        return $this->render('AppBundle::begin_order_for_download.html.twig', [
            'form'     => $form->createView(),
            'download' => $download,
        ]);
    }

OrderType 表单如下所示,为了演示目的保持简单。根据您的需要进行编辑。

    <?php

    namespace AppBundle\Form;

    use Symfony\Component\Form\AbstractType;
    use Symfony\Component\Form\FormBuilderInterface;

    class OrderType extends AbstractType
    {
        /**
         * {@inheritdoc}
         */
        public function getName()
        {
            return 'order';
        }

        /**
         * {@inheritdoc}
         */
        public function buildForm(FormBuilderInterface $builder, array $options)
        {
            $builder->add('email', 'repeated', [
                'type'            => 'email',
                'first_options'   => ['label' => 'Email'],
                'second_options'  => ['label' => 'Repeat Email'],
                'invalid_message' => 'The email fields must match.',
            ]);
            $builder->add('proceed', 'submit', ['attr' => ['class' => 'button']]);
        }
    }

如果表单有效,我们的订单将被持久化并且监听器为其分配一个订单号,然后我们将重定向 complete_order 路由。您可以在此处执行诸如提供付款详情之类的操作,或者在这种情况下,提供下载歌曲的链接。

就是这样。您可以在 https://github.com/adamelso/orda 查看完整工作示例的代码。

关于php - 如何在现有的 Symfony2 应用程序中实现 Sylius OrderBundle,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35896347/

有关php - 如何在现有的 Symfony2 应用程序中实现 Sylius OrderBundle的更多相关文章

  1. ruby - 如何在 Ruby 中顺序创建 PI - 2

    出于纯粹的兴趣,我很好奇如何按顺序创建PI,而不是在过程结果之后生成数字,而是让数字在过程本身生成时显示。如果是这种情况,那么数字可以自行产生,我可以对以前看到的数字实现垃圾收集,从而创建一个无限系列。结果只是在Pi系列之后每秒生成一个数字。这是我通过互联网筛选的结果:这是流行的计算机友好算法,类机器算法:defarccot(x,unity)xpow=unity/xn=1sign=1sum=0loopdoterm=xpow/nbreakifterm==0sum+=sign*(xpow/n)xpow/=x*xn+=2sign=-signendsumenddefcalc_pi(digits

  2. ruby - 在 Ruby 中实现 `call_user_func_array` - 2

    我怎样才能完成http://php.net/manual/en/function.call-user-func-array.php在ruby中?所以我可以这样做:classAppdeffoo(a,b)putsa+benddefbarargs=[1,2]App.send(:foo,args)#doesn'tworkApp.send(:foo,args[0],args[1])#doeswork,butdoesnotscaleendend 最佳答案 尝试分解数组App.send(:foo,*args)

  3. ruby - 将差异补丁应用于字符串/文件 - 2

    对于具有离线功能的智能手机应用程序,我正在为Xml文件创建单向文本同步。我希望我的服务器将增量/差异(例如GNU差异补丁)发送到目标设备。这是计划:Time=0Server:hasversion_1ofXmlfile(~800kiB)Client:hasversion_1ofXmlfile(~800kiB)Time=1Server:hasversion_1andversion_2ofXmlfile(each~800kiB)computesdeltaoftheseversions(=patch)(~10kiB)sendspatchtoClient(~10kiBtransferred)Cl

  4. ruby - 如何在 buildr 项目中使用 Ruby 代码? - 2

    如何在buildr项目中使用Ruby?我在很多不同的项目中使用过Ruby、JRuby、Java和Clojure。我目前正在使用我的标准Ruby开发一个模拟应用程序,我想尝试使用Clojure后端(我确实喜欢功能代码)以及JRubygui和测试套件。我还可以看到在未来的不同项目中使用Scala作为后端。我想我要为我的项目尝试一下buildr(http://buildr.apache.org/),但我注意到buildr似乎没有设置为在项目中使用JRuby代码本身!这看起来有点傻,因为该工具旨在统一通用的JVM语言并且是在ruby中构建的。除了将输出的jar包含在一个独特的、仅限ruby​​

  5. ruby - 什么是填充的 Base64 编码字符串以及如何在 ruby​​ 中生成它们? - 2

    我正在使用的第三方API的文档状态:"[O]urAPIonlyacceptspaddedBase64encodedstrings."什么是“填充的Base64编码字符串”以及如何在Ruby中生成它们。下面的代码是我第一次尝试创建转换为Base64的JSON格式数据。xa=Base64.encode64(a.to_json) 最佳答案 他们说的padding其实就是Base64本身的一部分。它是末尾的“=”和“==”。Base64将3个字节的数据包编码为4个编码字符。所以如果你的输入数据有长度n和n%3=1=>"=="末尾用于填充n%

  6. ruby-on-rails - 如何在 ruby​​ 中使用两个参数异步运行 exe? - 2

    exe应该在我打开页面时运行。异步进程需要运行。有什么方法可以在ruby​​中使用两个参数异步运行exe吗?我已经尝试过ruby​​命令-system()、exec()但它正在等待过程完成。我需要用参数启动exe,无需等待进程完成是否有任何ruby​​gems会支持我的问题? 最佳答案 您可以使用Process.spawn和Process.wait2:pid=Process.spawn'your.exe','--option'#Later...pid,status=Process.wait2pid您的程序将作为解释器的子进程执行。除

  7. ruby-on-rails - Rails 应用程序之间的通信 - 2

    我构建了两个需要相互通信和发送文件的Rails应用程序。例如,一个Rails应用程序会发送请求以查看其他应用程序数据库中的表。然后另一个应用程序将呈现该表的json并将其发回。我还希望一个应用程序将存储在其公共(public)目录中的文本文件发送到另一个应用程序的公共(public)目录。我从来没有做过这样的事情,所以我什至不知道从哪里开始。任何帮助,将不胜感激。谢谢! 最佳答案 无论Rails是什么,几乎所有Web应用程序都有您的要求,大多数现代Web应用程序都需要相互通信。但是有一个小小的理解需要你坚持下去,网站不应直接访问彼此

  8. ruby - 无法运行 Rails 2.x 应用程序 - 2

    我尝试运行2.x应用程序。我使用rvm并为此应用程序设置其他版本的ruby​​:$rvmuseree-1.8.7-head我尝试运行服务器,然后出现很多错误:$script/serverNOTE:Gem.source_indexisdeprecated,useSpecification.Itwillberemovedonorafter2011-11-01.Gem.source_indexcalledfrom/Users/serg/rails_projects_terminal/work_proj/spohelp/config/../vendor/rails/railties/lib/r

  9. ruby - 如何在续集中重新加载表模式? - 2

    鉴于我有以下迁移:Sequel.migrationdoupdoalter_table:usersdoadd_column:is_admin,:default=>falseend#SequelrunsaDESCRIBEtablestatement,whenthemodelisloaded.#Atthispoint,itdoesnotknowthatusershaveais_adminflag.#Soitfails.@user=User.find(:email=>"admin@fancy-startup.example")@user.is_admin=true@user.save!ende

  10. ruby-on-rails - Rails 应用程序中的 Rails : How are you using application_controller. rb 是新手吗? - 2

    刚入门rails,开始慢慢理解。有人可以解释或给我一些关于在application_controller中编码的好处或时间和原因的想法吗?有哪些用例。您如何为Rails应用程序使用应用程序Controller?我不想在那里放太多代码,因为据我了解,每个请求都会调用此Controller。这是真的? 最佳答案 ApplicationController实际上是您应用程序中的每个其他Controller都将从中继承的类(尽管这不是强制性的)。我同意不要用太多代码弄乱它并保持干净整洁的态度,尽管在某些情况下ApplicationContr

随机推荐