راهنمای توسعه‌دهندگان

Dima B2B Marketplace

فهرست مطالب

معرفی

این راهنما برای توسعه‌دهندگانی است که می‌خواهند در پروژه Dima B2B Marketplace مشارکت کنند یا آن را توسعه دهند.

ساختار کد

پوشه‌بندی

app/ ├── Core/ # کلاس‌های پایه │ ├── Router.php # سیستم مسیریابی │ ├── Controller.php # کلاس پایه کنترلر │ ├── Model.php # کلاس پایه مدل │ └── View.php # موتور نمایش ├── Controllers/ # کنترلرها ├── Models/ # مدل‌ها ├── Views/ # ویوها ├── Services/ # سرویس‌ها └── routes/ # فایل‌های مسیر

نام‌گذاری

  • کلاس‌ها: PascalCase (مثال: UserController)
  • متدها: camelCase (مثال: getUserData)
  • متغیرها: camelCase (مثال: $userName)
  • ثابت‌ها: UPPER_SNAKE_CASE (مثال: MAX_FILE_SIZE)
  • فایل‌ها: kebab-case (مثال: user-controller.php)

الگوی MVC

Model

<?php class Product extends Model { protected $table = 'products'; protected $fillable = ['name', 'description', 'price']; protected $hidden = ['created_at', 'updated_at']; public function category() { return $this->belongsTo(Category::class); } public function getPriceAttribute($value) { return number_format($value, 0, '.', ','); } }

View

<?php // app/Views/products/index.php ?> <div class="products-grid"> <?php foreach ($products as $product): ?> <div class="product-card"> <h3><?= htmlspecialchars($product['name']) ?></h3> <p><?= htmlspecialchars($product['description']) ?></p> <span class="price"><?= price($product['price']) ?></span> </div> <?php endforeach; ?> </div>

Controller

<?php class ProductController extends Controller { public function index() { $products = Product::where('status', 'active') ->orderBy('created_at', 'DESC') ->paginate(20); $this->view('products/index', [ 'products' => $products ]); } public function show($id) { $product = Product::find($id); if (!$product) { $this->redirect('/404'); } $this->view('products/show', [ 'product' => $product ]); } }

سیستم Route

تعریف Route

<?php // app/routes/web.php $router->get('/', 'HomeController@index'); $router->get('/products', 'ProductController@index'); $router->get('/products/{id}', 'ProductController@show'); $router->post('/products', 'ProductController@store'); $router->put('/products/{id}', 'ProductController@update'); $router->delete('/products/{id}', 'ProductController@delete');

Route Groups

$router->group('/admin', function($router) { $router->get('/', 'AdminController@index'); $router->get('/users', 'AdminController@users'); $router->get('/products', 'AdminController@products'); }, ['admin']);

Middleware

$router->middleware('auth', function() { if (!is_logged_in()) { redirect('/login'); return false; } return true; });

سرویس‌ها

ایجاد سرویس جدید

<?php class EmailService { private $smtpHost; private $smtpPort; private $username; private $password; public function __construct() { $this->smtpHost = get_setting('smtp_host'); $this->smtpPort = get_setting('smtp_port'); $this->username = get_setting('smtp_username'); $this->password = get_setting('smtp_password'); } public function send($to, $subject, $message) { // منطق ارسال ایمیل } }

استفاده از سرویس

$emailService = new EmailService(); $result = $emailService->send('user@example.com', 'موضوع', 'پیام');

پایگاه داده

Migration

<?php // migrations/create_products_table.php class CreateProductsTable { public function up() { $sql = " CREATE TABLE products ( id INT AUTO_INCREMENT PRIMARY KEY, name VARCHAR(255) NOT NULL, description TEXT, price DECIMAL(10,2) NOT NULL, category_id INT, status ENUM('active', 'inactive') DEFAULT 'active', created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP, updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, FOREIGN KEY (category_id) REFERENCES categories(id) ) "; global $db; $db->exec($sql); } public function down() { $sql = "DROP TABLE products"; global $db; $db->exec($sql); } }

Query Builder

$products = DB::table('products') ->select('name', 'price') ->where('status', 'active') ->where('price', '>', 100) ->orderBy('created_at', 'DESC') ->limit(10) ->get();

امنیت

CSRF Protection

// تولید توکن $token = generate_csrf_token(); // بررسی توکن if (!verify_csrf_token($_POST['csrf_token'])) { die('CSRF token mismatch'); }

SQL Injection Prevention

// استفاده از Prepared Statements $stmt = $db->prepare("SELECT * FROM users WHERE email = ?"); $stmt->execute([$email]); $user = $stmt->fetch();

XSS Prevention

// خروجی امن echo htmlspecialchars($userInput, ENT_QUOTES, 'UTF-8'); // یا استفاده از helper echo escape($userInput);

تست

Unit Tests

<?php // tests/ProductTest.php class ProductTest extends PHPUnit\Framework\TestCase { public function testProductCreation() { $product = new Product(); $product->name = 'Test Product'; $product->price = 100; $this->assertEquals('Test Product', $product->name); $this->assertEquals(100, $product->price); } public function testProductValidation() { $product = new Product(); $product->name = ''; $product->price = -10; $this->assertFalse($product->isValid()); } }

Integration Tests

<?php // tests/ProductControllerTest.php class ProductControllerTest extends PHPUnit\Framework\TestCase { public function testProductIndex() { $controller = new ProductController(); $result = $controller->index(); $this->assertInstanceOf('View', $result); } }

بهینه‌سازی

Caching

// کش ساده $cache = new Cache(); $key = 'products_list_' . $page; if (!$products = $cache->get($key)) { $products = Product::paginate(20, $page); $cache->set($key, $products, 3600); // 1 hour }

Database Optimization

// استفاده از Index $sql = "CREATE INDEX idx_products_status ON products(status)"; // بهینه‌سازی کوئری $products = Product::select('id', 'name', 'price') ->where('status', 'active') ->where('category_id', $categoryId) ->get();

Performance Monitoring

// اندازه‌گیری زمان اجرا $start = microtime(true); // کد شما $end = microtime(true); $executionTime = $end - $start; // لاگ کردن log_performance('product_index', $executionTime);

استانداردهای کدنویسی

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
  • پشتیبان‌گیری
  • مانیتورینگ
  • تست عملکرد
برای اطلاعات بیشتر به مستندات کامل مراجعه کنید.