PSR Standards
- PSR-1: Basic Coding Standard
- PSR-2: Coding Style Guide
- PSR-4: Autoloader
- PSR-12: Extended Coding Style
Code Style
<?php
declare(strict_types=1);
namespace App\Controllers;
use App\Models\Product;
use App\Services\EmailService;
class ProductController extends Controller
{
private $emailService;
public function __construct(EmailService $emailService)
{
$this->emailService = $emailService;
}
public function index(): void
{
$products = Product::where('status', 'active')
->orderBy('created_at', 'DESC')
->paginate(20);
$this->view('products/index', [
'products' => $products
]);
}
}
Documentation
/**
* نمایش لیست محصولات
*
* @param int $page شماره صفحه
* @return void
* @throws \Exception اگر صفحه معتبر نباشد
*/
public function index(int $page = 1): void
{
// کد متد
}
Error Handling
try {
$product = Product::find($id);
if (!$product) {
throw new ProductNotFoundException('محصول یافت نشد');
}
$product->delete();
} catch (ProductNotFoundException $e) {
$this->error('محصول یافت نشد', [], 404);
} catch (\Exception $e) {
log_error($e);
$this->error('خطای داخلی سرور', [], 500);
}
Best Practices
1. Single Responsibility Principle
❌ بد:
class UserController {
public function createUser() {
// ایجاد کاربر
// ارسال ایمیل
// ایجاد لاگ
// ارسال SMS
}
}
✅ خوب:
class UserController {
private $emailService;
private $smsService;
private $logger;
public function createUser() {
$user = $this->userService->create($data);
$this->emailService->sendWelcome($user);
$this->smsService->sendVerification($user);
$this->logger->log('user_created', $user);
}
}
2. Dependency Injection
❌ بد:
class ProductController {
public function __construct() {
$this->emailService = new EmailService();
}
}
✅ خوب:
class ProductController {
private $emailService;
public function __construct(EmailService $emailService) {
$this->emailService = $emailService;
}
}
3. Configuration Management
❌ بد:
$dbHost = 'localhost';
$dbName = 'marketplace';
$dbUser = 'root';
$dbPass = 'password';
✅ خوب:
$config = [
'database' => [
'host' => getenv('DB_HOST') ?: 'localhost',
'name' => getenv('DB_NAME') ?: 'marketplace',
'user' => getenv('DB_USER') ?: 'root',
'pass' => getenv('DB_PASS') ?: 'password'
]
];
Debugging
Logging
// لاگ ساده
log_info('User logged in', ['user_id' => $userId]);
// لاگ خطا
log_error('Database connection failed', [
'error' => $e->getMessage(),
'file' => $e->getFile(),
'line' => $e->getLine()
]);
// لاگ دیباگ
log_debug('Processing user data', $userData);
Debug Tools
// نمایش متغیر
dd($variable);
// نمایش و ادامه
dump($variable);
// نمایش اطلاعات کامل
var_dump($variable);
Deployment
Environment Setup
# کپی فایل محیط
cp .env.example .env
# تنظیم مجوزها
chmod 755 uploads/
chmod 755 logs/
chmod 644 .env
# نصب وابستگیها
composer install --no-dev --optimize-autoloader
# بهینهسازی
php artisan config:cache
php artisan route:cache
php artisan view:cache
Production Checklist
- تنظیمات امنیتی
- بهینهسازی پایگاه داده
- فعالسازی کش
- تنظیم SSL
- پشتیبانگیری
- مانیتورینگ
- تست عملکرد