# sfblog **Repository Path**: pppna/sfblog ## Basic Information - **Project Name**: sfblog - **Description**: symfony3博客 - **Primary Language**: Unknown - **License**: Not specified - **Default Branch**: master - **Homepage**: None - **GVP Project**: No ## Statistics - **Stars**: 1 - **Forks**: 2 - **Created**: 2015-12-28 - **Last Updated**: 2020-12-19 ## Categories & Tags **Categories**: Uncategorized **Tags**: None ## README README

第三讲: 创建初步用户系统

本课程(Symfony3开发实战)由phpna.com原创制作,版权所有,未经同意不得随意转载,违者必追求其法律责任

—讲师:lichnow 联系QQ:406879210

第三讲: 创建初步用户系统一,源代码下载及使用下载源代码配置应用安装应用切换到虚拟机安装应用二,课前准备设置导航栏为公用挂件在导航栏挂机模板中加入用户状态及权限判断功能必须阅读的文档三,课程操作使用FosUserBundle构建初级用户系统配置应用默认语言为中文继承创建自己的UserBundle覆盖FosUserBundle的模板覆盖模板覆盖修改密码控制器覆盖控制器覆盖密码重置控制器的事件监听器覆盖监听器覆盖表单构造器覆盖表单构造器使用用户组并使用UserManager管理用户注入初始数据添加路由并配置用户安全文件security.ml配置邮件发送服务器完成初级用户系统

一,源代码下载及使用

下载源代码

如没有克隆需先联系我把你的PC的SSH密匙加入私有GIT库,然后执行一下命令进行克隆

 
 
git clone git@git.oschina.net:phpna/sfblog.git {project_path}## 克隆源代码
cd {project_path} ## 打开源代码目录
git pull origin ## 更新库,使用下一步的源代码
git checkout step{x} ##切换到本一步分支

出现composer.lock文件没有提交无法切换分支的错误请执行以下命令

 
xxxxxxxxxx
 
git add .
git commit -m 'checkout step'

配置应用

 
x
 
# 复制配置模板为配置文件
cp app/config/parameters.yml.dist app/config/parameters.yml
# 切换到主机使用编辑器编辑配置文件
subl app/config/parameters.yml

安装应用

注意:如果使用Vagrant虚拟机作为运行环境,请切换到虚拟机执行以下步骤

切换到虚拟机

composer更新缓慢,可使用以下命令切换到国内镜像

composer config -g repo.packagist composer http://packagist.phpcomposer.com

 
xxxxxxxxxx
 
cd {vm_path}
vagrant ssh
su www-data ###如果没有配置www-data密码请先配置
cd /var/www/{project_path} ###在虚拟机中打开应用目录

安装应用

 
xxxxxxxxxx
 
# 安装类库
composer update 
# 如果上一步没有创建数据库,需先使用以下命令创建数据库
php bin/console doctrine:database:create
# 本课程每一步源代码使用都需重新生成数据库表结构
php bin/console doctrine:schema:update --force
#注入初始数据并且表ID从1重新开始
php bin/console h:d:f:l --purge-with-truncate

二,课前准备

设置导航栏为公用挂件

公用挂件可以在任何其它模板中调用而不需要在控制器中重新读取挂件数据,使用方法在这里

在BlogBundle中创建PublicController以及recentNavAction方法

 
xxxxxxxxxx
 
// src/BlogBundle/Controller/PublicController.php
<?php
...
class PublicController extends Controller
{
   /**
     * @Template("BlogBundle:Public:nav.html.twig")
     */
public function recentNavAction($path)
    {
        ....
    }
}

在layout.html.twig中加载挂件

 
xxxxxxxxxx
 
{# src/BlogBundle/Resources/views/layout.html.twig #}
......
{% block body %}
    {% if path is not defined %}{% set path = null %}{% endif %}
    {{ render(controller('BlogBundle:Public:recentNav',{'path': path})) }}
    ......
{% endblock %}

最后修改BlogBundle的IndexController控制器在Post和Index的模板数据中只要传入Path即可

在导航栏挂机模板中加入用户状态及权限判断功能

请查看src/BlogBundle/Resources/views/Public/nav.html.twig的源代码

必须阅读的文档

  1. 表单使用
  2. 验证
  3. 用户系统
  4. 本地化多国语言
  5. FosUserBundle

三,课程操作

使用FosUserBundle构建初级用户系统

  FosUserBundle是基于Symfony Security组件的一个完整的用户系统插件,构建了基本的用户登录,用户注册,邮箱验证,密码修改,密码重置,用户组等等功能。FosUserBundle具有高度DIY特性,你完全可以通过继承并修改FosUserBundle获得一个令自己满意的用户权限系统。安装及基本配置

配置应用默认语言为中文

 
xxxxxxxxxx
 
app/config/parameter.yml
parameters:
    ......
    app_locale: zh_CN
    ......
 
xxxxxxxxxx
 
app/config/config.yml
......
parameters:
    locale: %app_locale%
framework:
    #esi:             ~
    translator:      { fallbacks: ["%locale%"] }
    ......

继承创建自己的UserBundle

  php bin/console generate:bundle

 
xxxxxxxxxx
 
// src/UserBundle/UserBundle.php
<?php
...
  /**
  * 继承FosUserBundle
  */
  public function getParent()
  {
      return 'FOSUserBundle';
  }
...

覆盖FosUserBundle的模板覆盖模板

注意在使用覆盖模板的时候我们可以导入Symfony自带的bootstrap3表单主题使用,也可以自定义表单主题使用表单主题

 
xxxxxxxxxx
 
{% form_theme form "bootstrap_3_horizontal_layout.html.twig" %}

覆盖模板后必须使用php bin/console cache:clear命令清楚缓存方能生效

覆盖修改密码控制器覆盖控制器

src\UserBundle\Controller\ChangePasswordController.php

覆盖密码重置控制器的事件监听器覆盖监听器

创建监听器:src\UserBundle\EventListener\PasswordResettingListener.php

创建服务用于注入router服务:

 
xxxxxxxxxx
 
# src/UserBundle/Resources/config/services.yml
services:
    app.user.password_resetting:
        class: UserBundle\EventListener\PasswordResettingListener
        arguments: ['@router']
        tags:
            - { name: kernel.event_subscriber }

覆盖表单构造器覆盖表单构造器

覆盖构造器的主要目的是为了让表单提交后验证的警告或错误信息能在全表单使用,而不让其出现在字段之后,如下所示:

'error_bubbling' => true

必须创建服务使构造器生效

 
xxxxxxxxxx
 
#src/UserBundle/Resources/config/service.yml
services:
    app.form.registration:
        class: UserBundle\Form\RegistrationType
        tags:
            - { name: form.type, alias: app_user_registration }
    app.form.resetting:
        class: UserBundle\Form\ResettingType
        tags:
            - { name: form.type, alias: app_user_resetting }
    app.form.change_password:
        class: UserBundle\Form\ChangePasswordType
        tags:
            - { name: form.type, alias: app_user_change_password }

在config.yml中的fos_user配置中指定这些类

 
xxxxxxxxxx
 
#app/config/config.yml
fos_user:
    ......
    registration:
        confirmation:
            enabled: true
        form:
            type: UserBundle\Form\RegistrationType
    resetting:
        form:
            type: UserBundle\Form\ResettingType
    change_password:
        form:
            type: UserBundle\Form\ChangePasswordType

使用用户组并使用UserManager管理用户

用户管理(UserManager)在这里,用户组使用在这里

用户组实体: src/UserBundle/Form/Group.php

创建编写好后加入config.yml的fos_user配置

更改用户和用户组表名称为:users和groups

这里需要注意的是,如果你想把表名称改成user和group请这样做~~

@ORM\Table(name="`user`") @ORM\Table(name="`group`")

因为user和group是mysql的关键字,所以我们需要加上`` 来转义

注入初始数据

在FosUserBundle中同样可以使用Alice以及DoctrineFixtures来注入初始数据

在初始数据中,我们把权限ROLE的添加放在Group中,这样可以方便管理,因为FOS的User实体不仅会通过本身来验证ROLE,也会自动加载所属的Group来验证ROLE

在user.yml中我们通过加载应用的参数配置来生成管理员数据:

 
xxxxxxxxxx
 
# src/UserBundle/DataFixtures/ORM/user.yml
UserBundle\Entity\User:
    user{admin}:
        username: <{admin_username}>
        plainPassword: <{admin_password}>
        email: <{admin_email}>
        enabled: true
        groups: ['@groupsuper_admin']
    ......

管理员参数配置添加到app/parameters.yml中

 
xxxxxxxxxx
 
# app/config/parameters.yml
parameters:
    ......
    admin_username: lichnow
    admin_password: 123
    admin_email: admin@phpna.com

添加路由并配置用户安全文件security.ml

用户安全全部可配置项请看这里

 
xxxxxxxxxx
 
fos_user:
    resource: "@FOSUserBundle/Resources/config/routing/all.xml"
    prefix: /user
fos_user_group: 
#group路由在开发时参考使用,后台开发好后最好在后台管理用户组
    resource: "@FOSUserBundle/Resources/config/routing/group.xml"
    prefix: /group 

最好设置一个前缀,比如user,group等,然后需要把user路由的前缀加入到security.yml的check_path,login_path和logout.path中

 
xxxxxxxxxx
 
# app/config/security.yml
......
form_login:
    check_path: /user/login_check
    login_path: /user/login
......
logout:
    path: /user/logout
.....

配置邮件发送服务器

FosUserBundle中的邮件发送主要用于用户注册验证,用户密码重置等

Symfony邮件服务器配置及使用请看这里

建议使用QQ邮箱作为测试邮件发送服务器,QQ邮箱还可以配置域名邮箱,非常好用,在邮箱密码mailer_password中必须写入QQ邮箱的动态密匙,而非QQ密码,与FoxMail等客户端配置一样

 
x
 
#app/config/parameters.yml
parameters:
......
    mailer_transport: smtp
    mailer_host: 127.0.0.1
    mailer_user: admin@xxx.com
    mailer_password: 123
    mail_encryption: ssl   
    mail_port: 465   
    mailer_sendname: phpna.com
......

在config.yml中的fos_user的配置里添加邮箱配置

 
x
#app/config/config.yml
......
fos_user:
    ...
    service:
        mailer: fos_user.mailer.twig_swift
    from_email:
        address:        %mailer_user%
        sender_name:    %mailer_sendname%

在开发环境中为了方便使用我们往往禁用邮件发送

 
xxxxxxxxxx
 
#app/config/config_dev.yml
swiftmailer:
    disable_delivery: true

完成初级用户系统

为了方便版本控制我们复制一份app/parameters.yml为app/parameters.yml.dist

最后我们使用命令重新生成数据表和注入初始数据,并访问测试

 
xxxxxxxxxx
 
php bin/console doctrine:schema:update --force
php bin/console h:d:f:l --purge-with-truncate
undefined