我想通过这样的文件夹来分隔 Symfony 中的部分:
src
- Blog
-- Controller
-- Entity
-- Form
-- Repository
- Main
-- Controller
-- Entity
-- Form
-- Repository
使用 bundle 我不能在控制器和实体中使用注释,也不能在我的博客中单独使用 make:entity。有没有办法在 symfony 4 中创建这种结构?
我想通过这样的文件夹来分隔 Symfony 中的部分:
src
- Blog
-- Controller
-- Entity
-- Form
-- Repository
- Main
-- Controller
-- Entity
-- Form
-- Repository
使用 bundle 我不能在控制器和实体中使用注释,也不能在我的博客中单独使用 make:entity。有没有办法在 symfony 4 中创建这种结构?
由于 Symfony 是一个 PHP 框架并且不强加任何选择,只要Composer 自动加载器能够加载它们,您就可以自由地将您的类放置在您喜欢的任何地方。您可能还必须配置包以在其他命名空间/位置中查找对象。默认情况下,它们在您的应用程序中配置为从预定义的文件结构中加载。
例如,当您的实体位于 中时src/Blog/Entity/Post
,它可能应该具有完全限定的类名,例如App\Blog\Entity\Post
. 然后,您必须调整默认的 Doctrine 配置以加载具有此类命名空间的实体:
doctrine:
# ...
orm:
# ...
mappings:
Blog:
is_bundle: false
type: annotation
# before:
# dir: '%kernel.project_dir%/src/Entity'
# prefix: 'App\Entity'
# alias: App
# after:
dir: '%kernel.project_dir%/src/Blog/Entity'
prefix: 'App\Blog\Entity'
alias: Blog
另一个示例,您必须更改路由配置,以便它在以下位置查找控制器App\Blog\Controller
:
blog_routes:
resource: '../src/Blog/Controller/'
type: annotation
完全有可能,您最终会得到稍微复杂的配置:
# services for all src/*/ directories, ecxluding
App\:
resource: '../src/*'
exclude:
- ../src/Tests/
- ../src/Kernel.php
- '../src/*/{Entity,Migrations}'
App\Blog\Controller\:
resource: '../src/Blog/Controller'
tags: ['controller.service_arguments']
# repeat for other sub-directories
# App\Main\Controller\:
要使用 Maker Bundle,请为其指定更具体的路径
# config/packages/dev/maker.yaml
# create this file if you need to configure anything
maker:
# tell MakerBundle that all of your classes lives in an
# Acme namespace, instead of the default App
# (e.g. Acme\Entity\Article, Acme\Command\MyCommand, etc)
root_namespace: 'App\Blog\'
由于它仍然是同一个应用程序,因此您可以通过反转它并按部分对每种类型的类进行分组来避免“假包”布局:
src/
- Controller/
-- Blog/
-- Main/
- Entity
-- Blog/
-- Main/
这不需要对标准样式进行任何配置更改。