热门角色不仅是灵感来源,更是你的效率助手。通过精挑细选的角色提示词,你可以快速生成高质量内容、提升创作灵感,并找到最契合你需求的解决方案。让创作更轻松,让价值更直接!
我们根据不同用户需求,持续更新角色库,让你总能找到合适的灵感入口。
本提示词专为PHP开发者设计,能够根据指定的类名自动生成完整的对象实例化代码。它支持多种实例化场景,包括带参数构造、命名空间处理、异常捕获等常见开发需求。通过结构化的工作流程,确保生成的代码符合PHP最佳实践,具备良好的可读性和可维护性。适用于快速原型开发、教学演示和代码审查等多种PHP开发场景。
标题:App\Service\Mailer 的安全实例化(带参数构造,含参数验证与异常处理)
说明:本示例在保持 PSR-12 与可维护性的前提下,提供一个 Mailer 实例化工厂。参数来源于环境变量(避免硬编码凭证),并包含严格的参数校验与异常处理。
完整的PHP实例化代码
<?php
declare(strict_types=1);
namespace App\Service;
use InvalidArgumentException;
use RuntimeException;
use Throwable;
/**
* Mailer 实例化工厂。
*
* 约定构造函数签名:
* new Mailer(
* string $host = 'smtp.local',
* int $port = 587,
* bool $secure = true,
* string $username = 'noreply',
* string $password = 's3cr3t',
* array $options = ['timeout' => 5]
* )
*
* 注意:不要在代码中硬编码 password,示例通过环境变量注入。
*/
final class MailerFactory
{
/**
* 通过环境变量创建 Mailer 实例。
*
* 支持的环境变量:
* - SMTP_HOST (默认: smtp.local)
* - SMTP_PORT (默认: 587)
* - SMTP_SECURE (默认: true,接受 "1","0","true","false","yes","no")
* - SMTP_USERNAME (默认: noreply)
* - SMTP_PASSWORD (必填,无默认)
* - SMTP_TIMEOUT (默认: 5,单位秒)
*
* @throws RuntimeException|InvalidArgumentException 当配置不合法或实例化失败时抛出
*/
public function __invoke(): Mailer
{
$host = $this->normalizeHost($this->env('SMTP_HOST') ?? 'smtp.local');
$port = $this->normalizePort($this->env('SMTP_PORT'), 587);
$secure = $this->normalizeBool($this->env('SMTP_SECURE'), true);
$username = $this->normalizeUsername($this->env('SMTP_USERNAME') ?? 'noreply');
$password = $this->env('SMTP_PASSWORD');
if ($password === null || $password === '') {
throw new RuntimeException('Environment variable SMTP_PASSWORD is required and must not be empty.');
}
$timeout = $this->normalizeTimeout($this->env('SMTP_TIMEOUT'), 5);
$options = ['timeout' => $timeout];
try {
// 假设 App\Service\Mailer 已在同命名空间定义并通过 Composer 自动加载可用
return new Mailer($host, $port, $secure, $username, $password, $options);
} catch (Throwable $e) {
// 包装底层异常,避免泄漏敏感信息
throw new RuntimeException('Failed to instantiate Mailer with provided configuration.', 0, $e);
}
}
/**
* 获取环境变量:优先 $_ENV / $_SERVER,回退到 getenv()。
*/
private function env(string $key): ?string
{
if (array_key_exists($key, $_ENV)) {
return $_ENV[$key];
}
if (array_key_exists($key, $_SERVER)) {
return $_SERVER[$key];
}
$value = getenv($key);
return $value === false ? null : $value;
}
private function normalizeHost(string $host): string
{
$host = trim($host);
if ($host === '') {
throw new InvalidArgumentException('SMTP host must not be empty.');
}
return $host;
}
private function normalizePort(?string $raw, int $default): int
{
if ($raw === null || $raw === '') {
return $default;
}
$port = filter_var($raw, FILTER_VALIDATE_INT, [
'options' => ['min_range' => 1, 'max_range' => 65535],
]);
if ($port === false) {
throw new InvalidArgumentException('SMTP port must be a valid integer between 1 and 65535.');
}
return $port;
}
private function normalizeBool(?string $raw, bool $default): bool
{
if ($raw === null || $raw === '') {
return $default;
}
$val = filter_var($raw, FILTER_VALIDATE_BOOLEAN, FILTER_NULL_ON_FAILURE);
if ($val === null) {
throw new InvalidArgumentException('SMTP secure must be a boolean (true/false, 1/0, yes/no).');
}
return $val;
}
private function normalizeUsername(string $username): string
{
$username = trim($username);
if ($username === '') {
throw new InvalidArgumentException('SMTP username must not be empty.');
}
return $username;
}
private function normalizeTimeout(?string $raw, int $default): int
{
if ($raw === null || $raw === '') {
return $default;
}
$timeout = filter_var($raw, FILTER_VALIDATE_INT, [
'options' => ['min_range' => 1, 'max_range' => 120],
]);
if ($timeout === false) {
throw new InvalidArgumentException('SMTP timeout must be an integer between 1 and 120 seconds.');
}
return $timeout;
}
}
代码逻辑分步解析
使用注意事项和最佳实践建议
常见问题解决方案
如需我基于具体框架(如 Symfony/Laravel)给出容器配置与依赖注入示例,请告知使用的框架与版本。
标题:基于依赖注入的 OrderController 实例化(PSR 规范、异常处理与可维护性)
说明:以下代码展示了使用依赖注入创建 App\Http\Controller\OrderController 的标准做法。包含控制器定义、PSR-11 工厂类(推荐)、以及手动实例化示例。代码遵循 PSR-12、使用严格类型、并包含必要的异常处理与注释说明。
完整的PHP实例化代码
<?php
declare(strict_types=1);
namespace App\Http\Controller;
use Psr\Http\Message\ResponseFactoryInterface;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface;
use Psr\Log\LoggerInterface;
use App\Service\OrderService;
/**
* OrderController
*
* 通过依赖注入获取 LoggerInterface、OrderService 与 ResponseFactoryInterface。
* 示例包含一个简单的动作方法,展示服务调用与响应构建,包含必要的异常处理与日志记录。
*/
final class OrderController
{
public function __construct(
private readonly LoggerInterface $logger,
private readonly OrderService $service,
private readonly ResponseFactoryInterface $responseFactory
) {
}
/**
* 示例动作:创建订单
* - 从请求中读取数据
* - 调用应用服务创建订单
* - 返回 JSON 响应
*/
public function create(ServerRequestInterface $request): ResponseInterface
{
$response = $this->responseFactory->createResponse();
try {
$payload = $request->getParsedBody() ?? [];
// 建议在 OrderService 内部完成更严格的输入校验、事务与领域规则校验
$orderId = $this->service->createOrder($payload);
$response->getBody()->write(\json_encode(['id' => $orderId], JSON_THROW_ON_ERROR));
return $response
->withStatus(201)
->withHeader('Content-Type', 'application/json');
} catch (\DomainException $e) {
// 领域异常:可能是业务校验失败
$this->logger->warning('Order creation failed due to domain rule', [
'message' => $e->getMessage(),
]);
$response->getBody()->write(\json_encode(['error' => 'Invalid order data'], JSON_THROW_ON_ERROR));
return $response
->withStatus(400)
->withHeader('Content-Type', 'application/json');
} catch (\Throwable $e) {
// 未预期错误:记录错误并返回 500
$this->logger->error('Unexpected error during order creation', [
'exception' => $e,
]);
$response->getBody()->write(\json_encode(['error' => 'Server error'], JSON_THROW_ON_ERROR));
return $response
->withStatus(500)
->withHeader('Content-Type', 'application/json');
}
}
}
<?php
declare(strict_types=1);
namespace App\Http\Controller\Factory;
use App\Http\Controller\OrderController;
use App\Service\OrderService;
use Psr\Container\ContainerExceptionInterface;
use Psr\Container\ContainerInterface;
use Psr\Container\NotFoundExceptionInterface;
use Psr\Http\Message\ResponseFactoryInterface;
use Psr\Log\LoggerInterface;
/**
* OrderControllerFactory
*
* PSR-11 工厂,负责从容器解析依赖并实例化控制器。
* 在 Laminas/Mezzio/Slim/Symfony(自定义) 等框架中均可采用类似模式。
*/
final class OrderControllerFactory
{
/**
* @throws \RuntimeException 当依赖解析失败时抛出运行时异常
*/
public function __invoke(ContainerInterface $container): OrderController
{
try {
$logger = $container->get(LoggerInterface::class);
$service = $container->get(OrderService::class);
$responseFactory = $container->get(ResponseFactoryInterface::class);
} catch (NotFoundExceptionInterface|ContainerExceptionInterface $e) {
// 将容器错误封装为通用运行时异常,避免将容器细节泄漏到上层
throw new \RuntimeException('Failed to resolve dependencies for OrderController.', 0, $e);
}
return new OrderController($logger, $service, $responseFactory);
}
}
<?php
declare(strict_types=1);
// 手动实例化示例(在无容器或测试环境中)
use App\Http\Controller\OrderController;
use App\Service\OrderService;
use Psr\Http\Message\ResponseFactoryInterface;
use Psr\Log\LoggerInterface;
// 在真实项目中,请从应用上下文获取以下依赖对象:
/** @var LoggerInterface $logger */
$logger = /* your LoggerInterface instance */;
/** @var OrderService $service */
$service = /* your OrderService instance */;
/** @var ResponseFactoryInterface $responseFactory */
$responseFactory = /* your ResponseFactoryInterface instance */;
// 实例化控制器
$orderController = new OrderController($logger, $service, $responseFactory);
代码逻辑分步解析
命名空间与导入
控制器构造函数
动作方法示例 create()
工厂类 OrderControllerFactory
使用注意事项与最佳实践
优先使用 DI 容器
类型声明与严格类型
不要在控制器中做复杂业务
异常与日志
内容协商与响应
自动加载配置
常见问题与解决方案
问题:容器找不到依赖(NotFoundExceptionInterface)
问题:命名空间/自动加载错误导致类找不到
问题:JSON 编码失败或中文乱码
问题:测试环境如何实例化
问题:响应体已写入后再次写入
以上代码与说明可直接复制到项目中使用或做为基线模板进行扩展。
下面的示例展示如何在工厂模式下实例化 Domain\Repository\ProductRepository。代码遵循 PSR-12、严格类型、合理的异常封装与参数校验,避免硬编码敏感凭证,推荐从环境变量加载配置。
<?php
declare(strict_types=1);
namespace Domain\Repository\Exception;
use RuntimeException;
/**
* 封装仓储创建相关的异常,避免向上层泄露底层驱动细节和敏感信息
*/
final class RepositoryCreationException extends RuntimeException
{
}
namespace Domain\Repository;
use Domain\Repository\Exception\RepositoryCreationException;
use PDO;
use PDOException;
/**
* 产品仓储(示例)
* - 使用 PDO 连接数据库
* - 内置参数校验、DSN 构建与异常封装
*/
final class ProductRepository
{
private PDO $pdo;
/**
* @param string $driver 例如:mysql、pgsql、sqlite(默认 mysql)
* @param array<string, mixed> $config 连接配置:
* - mysql/pgsql: host, dbname, user, password[, port, charset]
* - sqlite: path
*
* 注意:不得在代码中硬编码敏感凭证(如 password)。请优先从环境变量或安全配置源加载。
*
* @throws RepositoryCreationException
*/
public function __construct(string $driver = 'mysql', array $config = [])
{
$this->pdo = $this->connect($driver, $config);
}
/**
* 示例:按主键查询产品
*
* @return array<string, mixed>|null
*/
public function findById(int $id): ?array
{
$stmt = $this->pdo->prepare('SELECT id, name, price FROM products WHERE id = :id');
$stmt->bindValue(':id', $id, PDO::PARAM_INT);
$stmt->execute();
$row = $stmt->fetch();
return $row !== false ? $row : null;
}
/**
* 建立 PDO 连接并返回实例
*
* @throws RepositoryCreationException
*/
private function connect(string $driver, array $config): PDO
{
$driver = strtolower($driver);
$allowedDrivers = ['mysql', 'pgsql', 'sqlite'];
if (!in_array($driver, $allowedDrivers, true)) {
throw new RepositoryCreationException(
"Unsupported driver '{$driver}'. Allowed: " . implode(', ', $allowedDrivers)
);
}
$config = $this->normalizeConfig($driver, $config);
[$dsn, $user, $password] = $this->buildDsn($driver, $config);
$options = [
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
PDO::ATTR_EMULATE_PREPARES => false,
];
try {
// 对于 sqlite,$user/$password 可为 null
return new PDO($dsn, $user, $password, $options);
} catch (PDOException $e) {
// 打包安全的配置,避免泄露密码
$safeConfig = $config;
if (isset($safeConfig['password'])) {
$safeConfig['password'] = '***redacted***';
}
$message = 'Failed to create PDO connection: ' . $e->getMessage()
. ' | config=' . json_encode($safeConfig, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE);
throw new RepositoryCreationException($message, (int) $e->getCode(), $e);
}
}
/**
* 规范化与校验配置,优先从环境变量读取缺失项
*
* @param array<string, mixed> $config
* @return array<string, mixed>
*
* @throws RepositoryCreationException
*/
private function normalizeConfig(string $driver, array $config): array
{
if ($driver === 'sqlite') {
$config['path'] = $config['path'] ?? ($_ENV['DB_PATH'] ?? getenv('DB_PATH') ?: '');
if ($config['path'] === '') {
throw new RepositoryCreationException('SQLite requires a non-empty "path" in config or DB_PATH env.');
}
return $config;
}
// 非 sqlite:从环境变量补全
$config['host'] = $config['host'] ?? ($_ENV['DB_HOST'] ?? getenv('DB_HOST') ?? '127.0.0.1');
$config['dbname'] = $config['dbname'] ?? ($_ENV['DB_NAME'] ?? getenv('DB_NAME') ?? null);
$config['user'] = $config['user'] ?? ($_ENV['DB_USER'] ?? getenv('DB_USER') ?? null);
$config['password'] = $config['password'] ?? ($_ENV['DB_PASSWORD'] ?? getenv('DB_PASSWORD') ?? '');
// 必填校验(避免空值导致隐式连接到错误库)
foreach (['host', 'dbname', 'user'] as $key) {
if (empty($config[$key]) || !is_string($config[$key])) {
throw new RepositoryCreationException("Invalid or missing '{$key}' in config.");
}
}
if (!is_string($config['password'])) {
throw new RepositoryCreationException('Invalid "password" type in config.');
}
// 基础字符校验,防止将恶意字符注入 DSN(密码不做字符限制)
$safePattern = '/^[A-Za-z0-9_\-\.]+$/';
if (!preg_match($safePattern, $config['host'])) {
throw new RepositoryCreationException('Host contains invalid characters.');
}
if (!preg_match($safePattern, $config['dbname'])) {
throw new RepositoryCreationException('Database name contains invalid characters.');
}
if (!preg_match('/^[\w\-.]+$/', $config['user'])) {
throw new RepositoryCreationException('User contains invalid characters.');
}
// 可选项:port, charset
$config['port'] = isset($config['port']) && is_int($config['port']) ? $config['port'] : null;
$config['charset'] = $config['charset'] ?? 'utf8mb4';
return $config;
}
/**
* 构建 DSN 及认证信息
*
* @param array<string, mixed> $config
* @return array{0:string,1:?string,2:?string} [dsn, user, password]
*/
private function buildDsn(string $driver, array $config): array
{
if ($driver === 'mysql') {
$dsn = sprintf(
'mysql:host=%s;%sdbname=%s;charset=%s',
$config['host'],
isset($config['port']) ? 'port=' . (int) $config['port'] . ';' : '',
$config['dbname'],
$config['charset']
);
return [$dsn, $config['user'], $config['password']];
}
if ($driver === 'pgsql') {
$dsn = sprintf(
'pgsql:host=%s;%sdbname=%s',
$config['host'],
isset($config['port']) ? 'port=' . (int) $config['port'] . ';' : '',
$config['dbname']
);
return [$dsn, $config['user'], $config['password']];
}
// sqlite
$dsn = 'sqlite:' . $config['path'];
return [$dsn, null, null];
}
}
namespace Domain\Factory;
use Domain\Repository\ProductRepository;
/**
* 仓储工厂:集中管理仓储实例的创建逻辑
*/
final class RepositoryFactory
{
/**
* @param string $driver
* @param array<string, mixed> $config
*/
public static function createProductRepository(string $driver = 'mysql', array $config = []): ProductRepository
{
// 如需扩展:可在此添加缓存、日志、代理包装等
return new ProductRepository($driver, $config);
}
}
// ========================= 使用示例(Client Code) =========================
// 说明:以下为用法示例,建议放在应用启动处(例如 bootstrap 或容器配置)。
// 实际项目中请使用 Composer PSR-4 自动加载,并通过 dotenv 或安全配置中心加载环境变量。
namespace App;
use Domain\Factory\RepositoryFactory;
use Domain\Repository\Exception\RepositoryCreationException;
$config = [
// 不要硬编码敏感信息;这里仅示例从环境加载,缺失项将由构造器进行校验并抛出异常
'host' => $_ENV['DB_HOST'] ?? getenv('DB_HOST') ?? '127.0.0.1',
'dbname' => $_ENV['DB_NAME'] ?? getenv('DB_NAME') ?? '',
'user' => $_ENV['DB_USER'] ?? getenv('DB_USER') ?? '',
'password' => $_ENV['DB_PASSWORD'] ?? getenv('DB_PASSWORD') ?? '',
// 'port' => 3306,
// 'charset'=> 'utf8mb4',
];
try {
$productRepository = RepositoryFactory::createProductRepository('mysql', $config);
// $product = $productRepository->findById(1);
} catch (RepositoryCreationException $e) {
// 记录日志并按需处理;避免向前端暴露内部错误细节
error_log($e->getMessage());
// 可在此回退或中止启动
}
命名空间与自动加载
工厂模式实例化
构造函数与依赖处理
安全与异常处理
示例方法
配置来源
PDO 驱动
连接配置
错误处理
代码质量
问:抛出 “Unsupported driver …”?
问:提示缺失 dbname/user?
问:PDOException: could not find driver
问:字符集乱码或表情符号无法存储
问:生产环境连接安全
问:如何与 DI 容器集成
以上方案严格遵守安全与可维护性要求,并采用工厂模式实现 ProductRepository 的标准化实例化流程。
打造一款面向PHP开发者的“一键对象实例化”智能提示词:用一次输入,自动产出可直接复制的高质量代码与讲解;覆盖带参构造、命名空间、错误处理等复杂情形;在原型开发、课堂演示、代码评审中显著提效;通过统一写法与清晰注释降低维护风险与新人上手成本,帮助个人与团队以更低试错成本快速验证价值并顺利完成付费落地。
用现成示例快速掌握对象创建与命名空间写法;按提示补齐参数与异常;完成课堂作业、学习笔记与小项目原型。
在迭代中一键产出模型、DTO、服务实例化片段;统一异常处理与注释风格;加速联调与功能落地。
用标准化片段复现与验证实例化逻辑;发现参数、依赖与边界问题;缩短Review往返,沉淀可复用示例库。
将模板生成的提示词复制粘贴到您常用的 Chat 应用(如 ChatGPT、Claude 等),即可直接对话使用,无需额外开发。适合个人快速体验和轻量使用场景。
把提示词模板转化为 API,您的程序可任意修改模板参数,通过接口直接调用,轻松实现自动化与批量处理。适合开发者集成与业务系统嵌入。
在 MCP client 中配置对应的 server 地址,让您的 AI 应用自动调用提示词模板。适合高级用户和团队协作,让提示词在不同 AI 工具间无缝衔接。
半价获取高级提示词-优惠即将到期