Symfony PHP 开发框架

精选 Symfony PHP 开发框架 常用指令与核心速查备忘单,涵盖高频用法、配置参数与实用技巧。

You can run php bin/console doctrine:schema:drop --强制执行 && php bin/console doctrine:schema:update --强制执行 && php bin/console doctrine:fixtures:load -n to Load data fixtures & reset sequence to 0


#数据库迁移指令 (Migration Commands)

CMD Description
bin/console make:migration Generate a new migration based on schema changes
bin/console doctrine:migration:generate Generate a new migration based on schema changes
bin/console doctrine:migration:migrate or php bin/console d:m:m Execute pending migrations to update the database
bin/console doctrine:migration:status Show status of migrations (pending, executed)
bin/console doctrine:migration:diff Compare current schema with the database and generate migration SQL

#Symfony Maker 代码生成器

#Maker-Bundle 生成指令列表 (Maker List)

命令指令 含义说明
bin/console list make List all make commands available
make:auth Create a Guard authenticator of different flavors
make:command Create a new console command class
make:controller Create a new controller class
make:crud Create CRUD for Doctrine entity class
make:docker:database Add a database container to your compose.yaml file
make:entity Create or update a Doctrine entity class, and 可选ly an API Platform resource
make:fixtures Create a new class to load Doctrine fixtures
make:form Create a new form class
make:functional-test Create a new test class
make:listener [make:subscriber] Creates a new event subscriber class or a new event listener class
make:message Create a new message and handler
make:messenger-middleware Create a new messenger middleware
make:migration Create a new migration based on database changes
make:registration-form Create a new registration form system
make:reset-password Create controller, entity, and repositories for use with symfonycasts/reset-password-bundle
make:schedule Create a scheduler component
make:security:custom Create a custom security authenticator
make:security:form-login Generate the code needed for the form_login authenticator
make:serializer:encoder Create a new serializer encoder class
make:serializer:normalizer Create a new serializer normalizer class
make:stimulus-controller Create a new Stimulus controller
make:subscriber Creates a new event subscriber class or a new event listener class
make:test [make:unit-test make:functional-test] Create a new test class
make:twig-component Create a Twig (or Live) component
make:twig-extension Create a new Twig extension with its runtime class
make:unit-test Create a new test class
make:user Create a new security user class
make:validator Create a new validator and constraint class
make:voter Create a new security voter class
make:webhook Create a new Webhook

#控制器开发基础 (Controller Basics)

#路由属性配置 (Route Attributes)

use Symfony\Component\Routing\Attribute\Route;

Attribute Description
#[Route('/path')] Define a route for a controller method
#[Route('/path', name: 'name')] Define a named route for a method
#[Route('/path', methods: ['GET'])] Define allowed HTTP methods
#[Route('/blog/{slug}')] Define a route with a parameter
#[Route('/page/{page}', requirements: ['page' => '\d+'])] Define a route with a parameter constraint
#[Route(path: ['en' => '/about-us', 'nl' => '/over-ons'], name: 'about')] Define localized routes

#AbstractController 核心方法 (Controller Methods)

Method Description
$this->render('template.html') Returns a Response with the rendered template
$this->redirectToRoute('homepage') Returns a RedirectResponse to a named route
$this->redirectToRoute('name', ['param' => 'value']) Returns a redirect to a route with parameters
$this->redirectToRoute('name', [], 301) Returns a RedirectResponse with status code
$this->redirect('http://example.com') Returns a RedirectResponse to an external URL
$this->createNotFoundException($msg) Returns a NotFoundHttpException
$this->createForm(FormType::class, $data) Creates a new Form instance based on the type

#Form 表单方法 (Form Methods)

Method Description
$form->handleRequest($request) Handle a form submission
$form->isSubmitted() Check if the form was submitted
$form->isValid() Check if the form is valid

#Form 表单控件类型 (Form Types) : Doc Symfony Form types

#文本输入框 (Text Fields)

TextType A basic text input field
TextareaType A multi-line textarea field
EmailType An email field (<input type="email">)
PasswordType A password field
SearchType A search field
UrlType A URL field (<input type="url">)
TelType A tel (phone number) input field
UuidType A UUID field

#数字与货币输入框 (Numeric Fields)

IntegerType A number field for integers
MoneyType A money field, with a specifiable currency
NumberType A number field
PercentType A number field for percentages
RangeType A range input field (slider)

#下拉选择与枚举框 (Choice Fields)

ChoiceType Field for selecting one or more options
EnumType Choose from PHP enum cases
EntityType Choose from a Doctrine entity
CountryType Choose a country
LanguageType Choose a language
LocaleType Choose a locale
TimezoneType Choose a timezone
CurrencyType Choose a currency

#Symfony UX 扩展字段 (UX Fields)

CropperType A Cropper.js image cropper field
DropzoneType A Dropzone file upload field

#日期与时间选择框 (Date & Time)

DateType A date field
DateIntervalType A date interval field
DateTimeType A date and time field
TimeType A time field
BirthdayType A date field for birthdays
WeekType Select a year and week

#基础布尔与文件框 (Other Fields)

CheckboxType A single checkbox field
FileType A file upload field
RadioType A radio button field
HiddenType A hidden field

#集合与重复控件组 (Field Groups)

CollectionType A group of fields that can be added or removed
RepeatedType A field that is repeated (e.g., password confirmation)

#数据校验属性与约束 (Validation Attributes) : Doc Symfony Validation

#⚙️ 基础断言约束 (Basic Constraints)

Attribute Description
#[Assert\NotBlank] Value is not an empty string/array, false or null
#[Assert\Blank] Value is an empty string or null
#[Assert\NotNull] Value is not strictly equal to null
#[Assert\IsNull] Value is exactly equal to null
#[Assert\Type('string')] Value is of a specific type

#数值比较约束 (Comparison Constraints)

Attribute Description
#[Assert\<Not>EqualTo('Foo')] Value is (not) equal to another value
#[Assert\<Not>IdenticalTo('Foo')] Value is (not) identical to another value
#[Assert\LessThan<OrEqual>(5)] Value is less than (or equal to) another value
#[Assert\GreaterThan<OrEqual>(5)] Value is greater than (or equal to) another value
#[Assert\Range(min: 2, max: 10)] Number or DateTime object is within a range

#字符串格式约束 (String Constraints)

Attribute Description
#[Assert\Length(2, 10)] String is between <min> and <max> characters long
#[Assert\Email] String is a valid email address
#[Assert\Url] String is a valid URL
#[Assert\Hostname] String is a valid hostname
#[Assert\Ip] String is a valid IP address
#[Assert\NoSuspiciousCharacters] String does not contain spoofing characters
#[Assert\Uuid] String is a valid UUID
#[Assert\CssColor] String is a valid CSS color

#日期与时间约束 (Date & Time Constraints)

Attribute Description
#[Assert\Date] Value is a valid date string in Y-m-d format
#[Assert\DateTime] Value is a valid datetime in the specified format
#[Assert\Time] Value is a valid time string in H:i:s format
#[Assert\Timezone] Value is a valid timezone identifier

#密码强度约束 (Password Constraints)

Attribute Description
#[Assert\UserPassword] String is the authenticated user's password
#[Assert\NotCompromisedPassword] Password is not found in any data breaches
#[Assert\PasswordStrength] Password has sufficient entropy

#金融与特定卡号约束 (Financial Constraints)

Attribute Description
#[Assert\Bic] Value is a valid Business Identifier Code (BIC)
#[Assert\CardScheme] Value is a valid credit card number
#[Assert\Currency] Value is a valid 3-letter ISO 4217 currency code
#[Assert\Luhn] Value passes the Luhn algorithm
#[Assert\Iban] Value is a valid IBAN
#[Assert\Isbn] Value is a valid ISBN

#文件上传约束 (File Constraints)

Attribute Description
#[Assert\File] Value is a valid file path or File object
#[Assert\Image] Same as File, but only accepts image MIME types

#正负数约束 (Number Constraints)

Attribute Description
#[Assert\Positive<OrZero>] Value is positive (or zero)
#[Assert\Negative<OrZero>] Value is negative (or zero)

#枚举与语言选择约束 (Choice Constraints)

Attribute Description
#[Assert\Choice(['A', 'B', 'C'])] Value is one of the specified choices
#[Assert\Country] Value is a valid ISO 3166-1 country code
#[Assert\Language] Value is a valid two-letter language code
#[Assert\Locale] Value is a valid locale identifier