n1c01a5/n1c0lesson-bundle

用于通过REST API管理课程的工具包

安装: 169

依赖: 0

建议者: 0

安全性: 0

星标: 0

关注者: 2

分支: 0

开放问题: 0

类型:symfony-bundle

dev-master 2016-01-09 15:47 UTC

This package is not auto-updated.

Last update: 2024-09-24 03:38:52 UTC


README

SensioLabsInsight

用于管理课程的工具包。

步骤1:设置工具包

A) 下载并安装 N1c0Lesson

要安装 N1c0Lesson,请运行以下命令

$ php composer.phar require n1c01a5/n1c0lesson-bundle

B) 启用工具包

在内核中启用所需的工具包

<?php
// app/AppKernel.php

public function registerBundles()
{
    $bundles = array(
        // ...
        new FOS\RestBundle\FOSRestBundle(),
        new JMS\SerializerBundle\JMSSerializerBundle(),
        new Nelmio\ApiDocBundle\NelmioApiDocBundle(),
        new Bazinga\Bundle\HateoasBundle\BazingaHateoasBundle(),
        new Stof\DoctrineExtensionsBundle\StofDoctrineExtensionsBundle(),
        new N1c0\LessonBundle\N1c0LessonBundle(),
    );
}

FOSRestBundle, StofDoctrineExtensionsBundle 和 NelmioApiDocBundle 必须配置。此工具包需要 PHP 的 Diff 实现:"sebastian/diff": "*" (composer.json).

C) 启用 Http 方法覆盖

如此处所述启用 HTTP 方法覆盖

从 symfony 2.3 开始,您只需修改您的 config.yml

# app/config/config.yml

framework:
    http_method_override: true

步骤2:设置 Doctrine ORM 映射

ORM 实现不提供供您使用的具体 Lesson 类,您必须自己创建一个。这可以通过扩展工具包提供的抽象实体并创建适当的映射来实现。

例如,课程实体

<?php
// src/MyProject/MyBundle/Entity/Lesson.php

namespace MyProject\MyBundle\Entity;

use Doctrine\ORM\Mapping as ORM;
use N1c0\LessonBundle\Entity\Lesson as BaseLesson;

/**
 * @ORM\Entity
 * @ORM\ChangeTrackingPolicy("DEFERRED_EXPLICIT")
 */
class Lesson extends BaseLesson
{
    /**
     * @ORM\Id
     * @ORM\Column(type="guid", length=36)
     * @ORM\GeneratedValue(strategy="UUID")
     */
    protected $id;
}

例如,参数实体

<?php
// src/MyProject/MyBundle/Entity/Argument.php

namespace MyProject\MyBundle\Entity;

use Doctrine\ORM\Mapping as ORM;
use N1c0\LessonBundle\Entity\Argument as BaseArgument;

/**
 * @ORM\Entity
 * @ORM\ChangeTrackingPolicy("DEFERRED_EXPLICIT")
 */
class Argument extends BaseArgument
{
    /**
     * @ORM\Id
     * @ORM\Column(type="guid", length=36)
     * @ORM\GeneratedValue(strategy="UUID")
     */
    protected $id;

    /**
     * Lesson of this argument
     *
     * @var Lesson 
     * @ORM\ManyToOne(targetEntity="MyProject\MyBundle\Entity\Argument")
     */
    protected $lesson;
}

添加到 app/config/config.yml

# N1c0LessonBundle
n1c0_lesson:
    db_driver: orm
    class:
        model:
            lesson: MyProject\MyBundle\Entity\Lesson
            argument: MyProject\MyBundle\Entity\Argument

entity_managers:
            default:
                mappings:
                    N1c0LessonBundle: ~
                    MyBundleMyProjectBundle: ~

assetic:
    bundles:        ["N1c0LessonBundle"]

步骤3:导入 N1c0LessonBundle 路由文件

# /app/config/routing.yml
n1c0_lesson:
    type: rest
    prefix: /api
    resource: "@N1c0Lesson/Resources/config/routing.yml"

内容协商

每个资源都可通过不同的格式访问。

HTTP 方法

对于课程

GET

HTML 格式

curl -i localhost:8000/api/v1/lessons/10

JSON 格式

curl -i -H "Accept: application/json" localhost:8000/api/v1/lessons/10

POST

HTML 格式

curl -X POST -d "n1c0_lesson_lesson%5Btitle%5D=myTitle&n1c0_lesson_lesson%5Bbody%5D=myBody" https://:8000/api/v1/lessons

JSON 格式

curl -X POST -d '{"n1c0_lesson_lesson":{"title":"myTitle","body":"myBody"}}' https://:8000/api/v1/lessons.json --header "Content-Type:application/json" -v

PUT

JSON 格式

curl -X PUT -d '{"n1c0_lesson_lesson":{"title":"myNewTitle","body":"myNewBody https://:8000/api/v1/lessons/10 --header "Content-Type:application/json" -v

对于参数

GET

JSON 格式

curl -i -H "Accept: application/json" localhost:8000/api/v1/lessons/10/arguments

POST

JSON 格式

curl -X POST -d '{"n1c0_lesson_argument":{"title":"myTitleArgument","body":"myBodyArgument"}}' https://:8000/api/v1/lessons/10/arguments.json --header "Content-Type:application/json" -v

PUT

JSON 格式

curl -X PUT -d '{"n1c0_lesson_argument":{"title":"myNewTitleArgument","body":"myNewBodyArgument"}}' https://:8000/api/v1/lessons/10/arguments/11.json --header "Content-Type:application/json" -v 

PATCH

JSON 格式

curl -X PATCH -d '{"n1c0_lesson_argument":{"title":"myNewTitleArgument"}}' https://:8000/api/v1/lessons/10/arguments/11.json --header "Content-Type:application/json" -v

HATEOAS REST

引入 HATEOAS 约束。

{
    "user": {
        "id": 10,
        "title": "myTitle",
        "body": "MyBody",
        "_links": {
            "self": { "href": "https://:8000/api/v1/lessons/10" }
        }
    }
}

FOSUserBundle 集成

默认情况下,课程是无名的。可以使用 FOSUserBundle 认证来签署课程。

A) 设置 FOSUserBundle

首先,您必须设置 FOSUserBundle。请查看 说明

B) 扩展 Lesson 类

为了向课程添加作者,Lesson 类应实现 SignedLessonInterface 并在映射中添加一个字段。

例如在 ORM

<?php
// src/MyProject/MyBundle/Entity/Lesson.php

namespace MyProject\MyBundle\Entity;

use Doctrine\ORM\Mapping as ORM;
use N1c0\LessonBundle\Entity\Lesson as BaseLesson;
use N1c0\LessonBundle\Model\SignedLessonInterface;
use Symfony\Component\Security\Core\User\UserInterface;

/**
 * @ORM\Entity
 */
class Lesson extends BaseLesson implements SignedLessonInterface
{
    // .. fields

    /**
     * Authors of the lesson
     *
     * @ORM\ManyToMany(targetEntity="Application\UserBundle\Entity\User")
     * @var User
     */
    protected $authors;

    public function __construct()
    {
        $this->authors = new \Doctrine\Common\Collections\ArrayCollection();
    }

    /**
     * Add author 
     *
     * @param Application\UserBundle\Entity\User $user
     */
    public function addAuthor(\Application\UserBundle\Entity\User $user)
    {
        $this->authors[] = $user;
    }

    /**
     * Remove user
     *
     * @param Application\UserBundle\Entity\User $user
     */
    public function removeUser(\Application\UserBundle\Entity\User $user)
    {
        $this->authorss->removeElement($user);
    }

    public function getAuthors()
    {
        return $this->authors;
    }

    public function getAuthorsName()
    {
        return $this->authors ?: parent::getAuthorsName(); 
    }
}

步骤7:添加基于角色的 ACL 安全性

注意

此工具包支持不同的安全设置。您还可以查看 添加 Symfony2 内置的 ACL 安全性

LessonBundle 还提供了根据特定用户拥有的角色配置权限的能力。请参阅下面的配置示例,了解如何自定义用于权限的默认角色。

要配置基于角色的安全性,请覆盖 Acl 服务

# app/config/config.yml

n1c0_lesson:
    acl: true
    service:
        acl:
            lesson:  n1c0_lesson.acl.lesson.roles
        manager:
            lesson:  n1c0_lesson.manager.lesson.acl

要更改特定操作所需的角色,修改 acl_roles 配置键

# app/config/config.yml

n1c0_lesson:
    acl_roles:
        lesson:
            create: IS_AUTHENTICATED_ANONYMOUSLY
            view: IS_AUTHENTICATED_ANONYMOUSLY
            edit: ROLE_ADMIN
            delete: ROLE_ADMIN

使用标记解析器

N1c0Lesson 工具包允许开发人员实现 RawLessonInterface,这将通知工具包您的课程将用于解析标记语言。

您还需要在数据库中配置一个 rawBody 字段以存储解析后的课程。

use N1c0\LessonBundle\Model\RawLessonInterface;

class Lesson extends BaseLesson implements RawLessonInterface
{
    /**
     * @ORM\Column(name="rawBody", type="text", nullable=true)
     * @var string
     */
    protected $rawBody;
    
    ... also add getter and setter as defined in the RawLessonInterface ...
}

当添加评论时,它会进行解析,并调用 setRawBody(),将评论的原始版本存储在数据库中,并在稍后渲染课程时显示。

支持任何标记语言,您只需要一个实现 Markup\ParserInterface 的桥梁类,它返回要显示在页面上的原始 html 格式的课程解析结果。

要设置自己的自定义标记解析器,您需要定义一个实现上述接口的服务,并通知N1c0LessonBundle,相应地调整配置。

# app/config/config.yml

n1c0_lesson:
    service:
        markup: your_markup_service

例如,使用Sundown PECL扩展作为标记服务

N1c0LessonBundle中的标记系统灵活,允许您使用任何解析器存在的语法语言。PECL有一个名为Sundown的markdown解析器扩展,比纯PHP实现的markdown解析器更快。

N1c0LessonBundle不附带此扩展的桥梁,但实现起来非常简单。

首先,您需要使用PECL安装Sundown。 pecl install sundown

您希望在您的应用程序包之一中创建以下服务。

<?php
// src/Vendor/LessonBundle/Markup/Sundown.php

namespace Vendor\LessonBundle\Markup;

use N1c0\LessonBundle\Markup\ParserInterface;
use Sundown\Markdown;

class Sundown implements ParserInterface
{
    private $parser;

    protected function getParser()
    {
        if (null === $this->parser) {
            $this->parser = new Markdown(
                new \Sundown\Render\HTML(array('filter_html' => true)),
                array('autolink' => true)
            );
        }

        return $this->parser;
    }

    public function parse($raw)
    {
        return $this->getParser()->render($raw);
    }
}

并定义服务以启用此解析器桥梁

# app/config/config.yml

services:
    # ...
    markup.sundown_markdown:
        class: Vendor\LessonBundle\Markup\Sundown
    # ...

n1c0_lesson:
    # ...
    service:
        markup: markup.sundown_markdown
    # ...

另一个例子,使用Pandoc作为标记服务

Pandoc是一个Haskell程序,允许您将文档从一种格式转换为另一种格式。更多信息请参阅Pandoc

要安装Pandoc,请运行以下命令

$ apt-get install pandoc

有关Pandoc安装的更多信息,请参阅Pandoc安装

我们还需要一个简单的PHP包装器。推荐使用composer安装Pandoc PHP。

{
    "require": {
        "ryakad/pandoc-php": "dev-master"
    }
}

安装完成后,您可以创建如下服务:

<?php

namespace vendor\LessonBundle\Markup;

use N1c0\LessonBundle\Markup\ParserInterface;
use Pandoc\Pandoc;

class MarkupPandoc implements ParserInterface
{
    private $parser;

    protected function getParser()
    {
        if (null === $this->parser) {
            $this->parser = new Pandoc();        
        }

        return $this->parser;
    }

    public function parse($raw)
    {
        return $this->getParser()->convert($raw, "markdown", "html");
    }
}

并定义服务以启用此解析器桥梁

# app/config/config.yml

services:
    # ...
    markup.pandoc_markdown:
        class: Vendor\LessonBundle\Markup\MarkupPandoc
    # ...

n1c0_lesson:
    # ...
    service:
        markup: markup.pandoc_markdown
    # ...

FOSCommentBundle集成

src/MyProject/MyBundle/Resources/views/Lesson/getLessons.html.twig中添加

<a href="{{ path('api_1_get_lesson_thread', {'id': lesson.id}) }}">Commentaires</a>

文档作为额外内容(NelmioApiDocBundle)

访问https://:8000/api/doc