প্রশ্ন ১ঃ php তে method overloading & method overriding কী এবং এটি কেন ব্যবহার করা হয়?
Answer:
🔹 Method Overriding:
📌 সংজ্ঞা:
Method Overriding হলো Parent class-এর method কে Child class-এ একই নামে (same signature) আবার define করা, যাতে child class নিজের মতো করে behavior change করতে পারে।
💻 উদাহরণ:
class Animal {
public function sound() {
echo "Animal makes sound";
}
}
class Dog extends Animal {
public function sound() {
echo "Dog barks";
}
}
$obj = new Dog();
$obj->sound(); // Output: Dog barks
🎯 কেন ব্যবহার করা হয়:
- Parent behavior modify/customize করতে
- Runtime Polymorphism implement করতে
- Clean & flexible OOP design করার জন্য
🔹 Method Overloading:
📌 সংজ্ঞা:
Method Overloading বলতে বুঝায় একই method name কিন্তু different parameters দিয়ে multiple method তৈরি করা।
👉 তবে PHP-তে traditional overloading নেই, তাই Magic Method (__call) দিয়ে simulate করা হয়।
💻 উদাহরণ:
class MathOperation {
public function __call($name, $arguments) {
if ($name == 'add') {
return array_sum($arguments);
}
}
}
$obj = new MathOperation();
echo $obj->add(2, 3); // 5
echo $obj->add(2, 3, 4); // 9
🎯 কেন ব্যবহার করা হয়:
- Flexible function call handle করতে
- Variable number of arguments support করতে
- Dynamic behavior implement করতে 🔥 মূল পার্থক্য (Interview Ready):
| বিষয় | Overriding | Overloading |
|---|---|---|
| কোথায় হয় | Parent → Child class | একই class-এ |
| Method name | Same | Same |
| Parameters | Same | Different |
| PHP Support | Native support আছে | Magic method দিয়ে simulate |
| উদ্দেশ্য | Behavior change | Flexible input handling |
🔚 Short Professional Answer (Interview):
👉
Method Overriding হলো inheritance-এ parent class-এর method কে child class-এ redefine করে behavior change করা।
আর Method Overloading হলো একই method name ব্যবহার করে different parameters handle করা, যা PHP-তে magic method (__call) দিয়ে achieve করা হয়।
👉 এগুলো ব্যবহার করা হয় polymorphism, code reusability, এবং flexible design implement করার জন্য।
প্রশ্ন 2: php তে trait কী এবং এটি কেন ব্যবহার করা হয়?
Answer:
🔹 Trait কী?
Trait হলো PHP-এর একটি code reuse mechanism যা multiple classes-এ common functionality share করার জন্য ব্যবহৃত হয়। এটি multiple inheritance এর সীমাবদ্ধতা কাটিয়ে ওঠার জন্য তৈরি করা হয়েছে।
PHP-তে একাধিক class inherit করা যায় না (single inheritance supported), কিন্তু একাধিক trait ব্যবহার করে সেই সমস্যা সমাধান করা যায়।
🔹 Trait এর Basic Syntax:
trait Logger {
public function log($message) {
echo "Log: " . $message;
}
}
class User {
use Logger;
}
$obj = new User();
$obj->log("User created."); // Output: Log: User created.
🔹 কেন Trait ব্যবহার করা হয়?
1. ✅ Code Reuse:
একই function অনেকগুলো class-এ লাগলে বারবার না লিখে trait এ একবার লিখে use করা যায়।
2. ✅ Multiple Trait Support:
একাধিক trait একসাথে use করা যায় (যা multiple inheritance-এর বিকল্প)।
3. ✅ Clean Architecture:
Trait ব্যবহার করে code-organizing structure অনেক পরিষ্কার রাখা যায়।
4. ✅ Avoid Duplication:
DRY (Don't Repeat Yourself) principle বজায় রাখতে সাহায্য করে।
🔹 একাধিক Trait ব্যবহার:
trait Logger {
public function log($msg) {
echo "Logging: $msg\n";
}
}
trait Notifier {
public function notify($msg) {
echo "Notifying: $msg\n";
}
}
class Admin {
use Logger, Notifier;
}
$a = new Admin();
$a->log("Admin logged in");
$a->notify("New user registered");
🔹 যখন একই method নাম থাকে:
trait A {
public function hello() {
echo "Hello from A";
}
}
trait B {
public function hello() {
echo "Hello from B";
}
}
class MyClass {
use A, B {
B::hello insteadof A; // B এর method override করবে A কে
A::hello as helloFromA; // A এর method alias হিসেবে থাকবে
}
}
🔚 উপসংহার:
| বিষয় | ব্যাখ্যা |
|---|---|
| Trait কী | Code reuse করার জন্য ব্যবহৃত PHP এর একটি feature |
| কবে ব্যবহার করবেন | যখন একাধিক class-এ একই function দরকার |
| প্রধান সুবিধা | Multiple inheritance-এর সীমাবদ্ধতা কাটিয়ে ওঠে |
প্রশ্ন ৩ঃ Method Overriding & Method Overloading কী এবং এটি কেন ব্যবহার করা হয়?
Answer:
🔹 Method Overriding:
📌 সংজ্ঞা:
Method Overriding হলো Parent class-এর method কে Child class-এ একই নামে (same signature) আবার define করা, যাতে child class নিজের মতো করে behavior change করতে পারে।
💻 উদাহরণ:
class Animal {
public function sound() {
echo "Animal makes sound";
}
}
class Dog extends Animal {
public function sound() {
echo "Dog barks";
}
}
$obj = new Dog();
$obj->sound(); // Output: Dog barks
🎯 কেন ব্যবহার করা হয়:
- Parent behavior modify/customize করতে
- Runtime Polymorphism implement করতে
- Clean & flexible OOP design করার জন্য
🔹 Method Overloading:
📌 সংজ্ঞা:
Method Overloading বলতে বুঝায় একই method name কিন্তু different parameters দিয়ে multiple method তৈরি করা।
👉 তবে PHP-তে traditional overloading নেই, তাই Magic Method (__call) দিয়ে simulate করা হয়।
💻 উদাহরণ:
class MathOperation {
public function __call($name, $arguments) {
if ($name == 'add') {
return array_sum($arguments);
}
}
}
$obj = new MathOperation();
echo $obj->add(2, 3); // 5
echo $obj->add(2, 3, 4); // 9
🎯 কেন ব্যবহার করা হয়:
- Flexible function call handle করতে
- Variable number of arguments support করতে
- Dynamic behavior implement করতে 🔥 মূল পার্থক্য (Interview Ready):
| বিষয় | Overriding | Overloading |
|---|---|---|
| কোথায় হয় | Parent → Child class | একই class-এ |
| Method name | Same | Same |
| Parameters | Same | Different |
| PHP Support | Native support আছে | Magic method দিয়ে simulate |
| উদ্দেশ্য | Behavior change | Flexible input handling |
🔚 Short Professional Answer (Interview):
👉
Method Overriding হলো inheritance-এ parent class-এর method কে child class-এ redefine করে behavior change করা।
আর Method Overloading হলো একই method name ব্যবহার করে different parameters handle করা, যা PHP-তে magic method (__call) দিয়ে achieve করা হয়।
👉 এগুলো ব্যবহার করা হয় polymorphism, code reusability, এবং flexible design implement করার জন্য।
প্রশ্ন ৪ঃ PHP-তে OOP (Object-Oriented Programming) এর principles গুলো ব্যাখ্যা করো
PHP-তে OOP মূলত ৪টি প্রধান principle এর উপর ভিত্তি করে:
🔹 ১. Encapsulation (এনক্যাপসুলেশন)
📌 সংজ্ঞা:
Data (properties) এবং method (functions) কে একসাথে একটি class-এর মধ্যে রাখা এবং access control (public, private, protected) ব্যবহার করে data hide করা।
💻 উদাহরণ:
class User {
private $name;
public function setName($name) {
$this->name = $name;
}
public function getName() {
return $this->name;
}
}
🎯 কেন ব্যবহার করা হয়:
- Data নিরাপদ রাখতে
- Controlled access দিতে
- Code maintainability বাড়াতে
🔹 ২. Inheritance (ইনহেরিটেন্স)
📌 সংজ্ঞা:
একটি class (child) অন্য একটি class (parent) এর properties ও methods inherit করে।
💻 উদাহরণ:
class Animal {
public function eat() {
echo "Eating...";
}
}
class Dog extends Animal {
public function bark() {
echo "Barking...";
}
}
🎯 কেন ব্যবহার করা হয়:
- Code reuse করার জন্য
- Hierarchical relationship তৈরি করতে
- Duplicate code কমাতে
🔹 ৩. Polymorphism (পলিমরফিজম)
📌 সংজ্ঞা:
একই method নাম, কিন্তু ভিন্ন ভিন্ন behavior (different implementation) — সাধারণত method overriding এর মাধ্যমে হয়।
💻 উদাহরণ:
class Shape {
public function draw() {
echo "Drawing shape";
}
}
class Circle extends Shape {
public function draw() {
echo "Drawing circle";
}
}
🎯 কেন ব্যবহার করা হয়:
- Flexible ও scalable code design করতে
- Same interface দিয়ে different কাজ করতে
🔹 ৪. Abstraction (অ্যাবস্ট্রাকশন)
📌 সংজ্ঞা:
শুধু প্রয়োজনীয় তথ্য দেখানো এবং implementation details hide করা — সাধারণত abstract class বা interface দিয়ে করা হয়।
💻 উদাহরণ:
abstract class Vehicle {
abstract public function start();
}
class Car extends Vehicle {
public function start() {
echo "Car starting...";
}
}
🎯 কেন ব্যবহার করা হয়:
- Complex system simplify করতে
- Standard structure enforce করতে
- Loose coupling তৈরি করতে 🔥 সংক্ষেপে (Interview Table):
| Principle | মূল কাজ |
|---|---|
| Encapsulation | Data hide & control access |
| Inheritance | Code reuse |
| Polymorphism | Same method, different behavior |
| Abstraction | Only essential show, details hide |
🎯 Short Professional Answer (Interview):
👉
PHP OOP-এর ৪টি মূল principle হলো Encapsulation, Inheritance, Polymorphism, এবং Abstraction।
Encapsulation data hide করে, Inheritance code reuse করে, Polymorphism একই method দিয়ে ভিন্ন behavior দেয়, এবং Abstraction complex logic hide করে simple interface দেয়।
প্রশ্ন ৫ঃ PHP-তে Abstract, Interface, Trait, Namespace কী, কেন ও কোথায় ব্যবহার করা হয়? (উদাহরণসহ)
Answer:
🔹 ১. Abstract Class
📌 কী:
Abstract class হলো এমন একটি class যেটি directly object create করা যায় না, বরং অন্য class এটিকে extend করে ব্যবহার করে। এতে abstract (body ছাড়া) এবং normal method দুটোই থাকতে পারে।
💻 উদাহরণ:
abstract class Animal {
abstract public function sound();
public function eat() {
echo "Eating...";
}
}
class Dog extends Animal {
public function sound() {
echo "Dog barks";
}
}
🎯 কেন ও কোথায় ব্যবহার:
- Common base structure define করতে
- Partial implementation দিতে
- যখন কিছু method অবশ্যই child class-এ implement করতে হবে
🔹 ২. Interface
📌 কী:
Interface হলো একটি contract, যেখানে শুধু method declaration থাকে (body থাকে না)। Class-কে বাধ্য করে সব method implement করতে।
💻 উদাহরণ:
interface Payment {
public function pay($amount);
}
class BkashPayment implements Payment {
public function pay($amount) {
echo "Paid via bKash: $amount";
}
}
🎯 কেন ও কোথায় ব্যবহার:
- Standard structure enforce করতে
- Multiple interface implement করা যায়
- Loose coupling ও scalable architecture-এ
🔹 ৩. Trait
📌 কী:
Trait হলো code reuse mechanism, যা multiple class-এ common method share করতে ব্যবহৃত হয়।
💻 উদাহরণ:
trait Logger {
public function log($msg) {
echo "Log: $msg";
}
}
class User {
use Logger;
}
🎯 কেন ও কোথায় ব্যবহার:
- Duplicate code avoid করতে
- Multiple inheritance limitation কাটাতে
- Helper/common functionality share করতে
🔹 ৪. Namespace
📌 কী:
Namespace হলো code organize করার একটি উপায়, যাতে same class name conflict এড়ানো যায়।
💻 উদাহরণ:
namespace App\Models;
class User {
public function info() {
echo "User Model";
}
}
ব্যবহার:
use App\Models\User;
$obj = new User();
🎯 কেন ও কোথায় ব্যবহার:
- Large project-এ code organize করতে
- Class name conflict avoid করতে
- PSR standard maintain করতে (Laravel-এ খুব গুরুত্বপূর্ণ)
🔥 সংক্ষেপে পার্থক্য:
| বিষয় | Abstract | Interface | Trait | Namespace |
|---|---|---|---|---|
| Type | Class | Contract | Code reuse | Organization |
| Method body | থাকতে পারে | থাকে না | থাকে | N/A |
| Multiple use | ❌ | ✅ | ✅ | ✅ |
| ব্যবহার | Base class | Structure enforce | Reuse logic | Code organize |
🎯 Short Professional Answer (Interview):
👉
Abstract class base structure দেয়,
Interface contract enforce করে,
Trait code reuse করে,
আর Namespace code organize করে এবং naming conflict এড়ায়।
👉 এগুলো ব্যবহার করা হয় clean, scalable, maintainable architecture তৈরি করার জন্য।
Explain with a real Laravel project example (Repository pattern, Service layer, etc.)
🚀 Real Laravel Example (Repository + Service Pattern)
ধরি আমরা একটি User Management System বানাচ্ছি।
📁 Project Structure
app/
├── Interfaces/
│ └── UserRepositoryInterface.php
├── Repositories/
│ └── UserRepository.php
├── Services/
│ └── UserService.php
├── Traits/
│ └── ApiResponseTrait.php
├── Models/
│ └── User.php
└── Http/Controllers/
└── UserController.php
🔹 ১. Interface (Contract define)
👉 app/Interfaces/UserRepositoryInterface.php
namespace App\Interfaces;
interface UserRepositoryInterface {
public function getAll();
public function findById($id);
public function create(array $data);
}
🎯 কেন:
- সব repository একই structure follow করবে
- Loose coupling (Controller → Interface, not concrete class)
🔹 ২. Repository (Implementation)
👉 app/Repositories/UserRepository.php
namespace App\Repositories;
use App\Interfaces\UserRepositoryInterface;
use App\Models\User;
class UserRepository implements UserRepositoryInterface {
public function getAll() {
return User::all();
}
public function findById($id) {
return User::findOrFail($id);
}
public function create(array $data) {
return User::create($data);
}
}
🎯 কেন:
- Database logic আলাদা রাখা
- Easily switch করা যায় (MySQL → API → অন্য source)
🔹 ৩. Service Layer (Business Logic)
👉 app/Services/UserService.php
namespace App\Services;
use App\Interfaces\UserRepositoryInterface;
class UserService {
protected $userRepo;
public function __construct(UserRepositoryInterface $userRepo) {
$this->userRepo = $userRepo;
}
public function getUsers() {
return $this->userRepo->getAll();
}
public function createUser($data) {
// business logic
$data['name'] = strtoupper($data['name']);
return $this->userRepo->create($data);
}
}
🎯 কেন:
- Business logic isolate করা
- Controller slim রাখা
🔹 ৪. Trait (Reusable Logic)
👉 app/Traits/ApiResponseTrait.php
namespace App\Traits;
trait ApiResponseTrait {
public function success($data, $message = "Success") {
return response()->json([
'status' => true,
'message' => $message,
'data' => $data
]);
}
}
🎯 কেন:
- বারবার response format না লিখে reuse করা
🔹 ৫. Controller (সব একসাথে ব্যবহার)
👉 app/Http/Controllers/UserController.php
namespace App\Http\Controllers;
use App\Services\UserService;
use App\Traits\ApiResponseTrait;
class UserController extends Controller {
use ApiResponseTrait;
protected $userService;
public function __construct(UserService $userService) {
$this->userService = $userService;
}
public function index() {
$users = $this->userService->getUsers();
return $this->success($users);
}
}
🔹 ৬. Service Container Binding
👉 AppServiceProvider.php
use App\Interfaces\UserRepositoryInterface;
use App\Repositories\UserRepository;
public function register() {
$this->app->bind(UserRepositoryInterface::class, UserRepository::class);
}
🔥 এখানে কোথায় কী ব্যবহার হলো?
| Concept | কোথায় ব্যবহার হয়েছে | কেন |
|---|---|---|
| Interface | UserRepositoryInterface | Contract define |
| Abstract (conceptually) | Interface/Service design | Structure enforce |
| Trait | ApiResponseTrait | Code reuse |
| Namespace | সব file-এর উপরে | Code organize |
| Repository | DB logic isolate | Clean architecture |
| Service | Business logic | Maintainable code |
🎯 Interview Ready Explanation:
👉
“In Laravel project, I use Interface + Repository pattern to decouple database logic, Service layer for business logic, Trait for reusable functionalities like API response, and Namespace to organize code properly. This makes the application scalable, testable, and maintainable.”
💡 যদি তুমি এটা interview-তে এভাবে explain করো + structure draw করো, তুমি easily standout করবে 🔥
প্রশ্ন 6: What is reqire & include in php?
Answer:
PHP-তে require এবং include হলো এমন দুইটি স্টেটমেন্ট, যেগুলো দিয়ে এক ফাইলের কোড অন্য ফাইলে ব্যবহার করা হয়।
1️⃣ include কী?
include দিয়ে কোনো PHP ফাইল যুক্ত (add) করা হয়।
যদি ফাইলটি না পাওয়া যায়, তাহলে warning দেখায়, কিন্তু স্ক্রিপ্ট চালু থাকে।
উদাহরণ:
include "header.php";
বৈশিষ্ট্য:
- ফাইল না থাকলে → Warning দেখাবে
- বাকি কোড এক্সিকিউট হবে
- কম গুরুত্বপূর্ণ ফাইলের জন্য ব্যবহার করা হয়
2️⃣ require কী?
require দিয়েও ফাইল যুক্ত করা হয়।
কিন্তু ফাইল না পাওয়া গেলে fatal error দেখায় এবং স্ক্রিপ্ট বন্ধ হয়ে যায়।
উদাহরণ:
require "config.php";
বৈশিষ্ট্য:
- ফাইল না থাকলে → Fatal Error
- পুরো স্ক্রিপ্ট বন্ধ হয়ে যায়
- খুব গুরুত্বপূর্ণ ফাইলের জন্য ব্যবহার করা হয়
🔑 include vs require পার্থক্য
| বিষয় | include | require |
|---|---|---|
| ফাইল না পেলে | Warning | Fatal Error |
| স্ক্রিপ্ট চলবে? | হ্যাঁ | না |
| ব্যবহার | কম গুরুত্বপূর্ণ ফাইল | গুরুত্বপূর্ণ ফাইল |
3️⃣ include_once ও require_once
একই ফাইল বারবার লোড হওয়া থেকে বাঁচাতে ব্যবহার করা হয়।
include_once "header.php";
require_once "config.php";
✔ ফাইল একবারই লোড হবে
✔ function / class redeclare error এড়ানো যায়
📌 কখন কোনটা ব্যবহার করবেন?
-
Database config / security file →
require/require_once -
Header, footer, template →
include/include_once
প্রশ্ন ৭: Multiple inheritance vs multilevel inheritance?
Answer:
🔹 Multilevel Inheritance
📌 কী:
Multilevel inheritance হলো একটি class → আরেকটি class → আরেকটি class এইভাবে chain আকারে inheritance হওয়া।
👉 অর্থাৎ:
Grandparent → Parent → Child
💻 উদাহরণ (PHP):
class Animal {
public function eat() {
echo "Eating...";
}
}
class Dog extends Animal {
public function bark() {
echo "Barking...";
}
}
class BabyDog extends Dog {
public function weep() {
echo "Weeping...";
}
}
$obj = new BabyDog();
$obj->eat(); // Animal থেকে
$obj->bark(); // Dog থেকে
$obj->weep(); // নিজস্ব method
🎯 কেন ব্যবহার করা হয়:
- Hierarchical structure তৈরি করতে
- Step-by-step inheritance
- Code reuse বাড়াতে
🔹 Multiple Inheritance
📌 কী:
Multiple inheritance হলো একটি class একাধিক parent class থেকে inherit করা।
👉 অর্থাৎ:
Parent1 + Parent2 → Child
❗ PHP-তে কি সম্ভব?
👉 সরাসরি possible না (PHP supports single inheritance only)
💡 তাহলে কীভাবে করা হয়?
👉 Trait ব্যবহার করে multiple inheritance-এর মতো behavior achieve করা হয়।
💻 উদাহরণ (Trait দিয়ে):
trait A {
public function methodA() {
echo "Method A";
}
}
trait B {
public function methodB() {
echo "Method B";
}
}
class MyClass {
use A, B;
}
$obj = new MyClass();
$obj->methodA();
$obj->methodB();
🎯 কেন ব্যবহার করা হয়:
- Multiple source থেকে functionality নিতে
- Code reuse বাড়াতে
- Complex behavior combine করতে
🔥 মূল পার্থক্য:
| বিষয় | Multilevel Inheritance | Multiple Inheritance |
|---|---|---|
| Structure | Chain (A → B → C) | Multiple parents (A + B → C) |
| PHP Support | ✅ আছে | ❌ নেই (Trait দিয়ে simulate) |
| Complexity | কম | বেশি |
| ব্যবহার | Hierarchy তৈরি | Multiple feature combine |
🎯 Short Interview Answer:
👉
Multilevel inheritance হলো chain আকারে inheritance (A → B → C),
আর Multiple inheritance হলো একাধিক parent class থেকে inherit করা (A + B → C)।
👉 PHP-তে multilevel supported, কিন্তু multiple inheritance directly supported না — Trait দিয়ে achieve করা হয়।
প্রশ্ন ৮ ঃ laravel এ clouser কি? কেন ব্যবহার করা হয়? কোন প্রবলেম টা সলভ করে?
Php তে clouser & magic method কি?
Answer:
দুইটা টপিকই PHP-তে খুব গুরুত্বপূর্ণ 👍
আমি সহজভাবে Closure আর Magic Method—দুটোই উদাহরণসহ বুঝিয়ে দিচ্ছি।
🔹 1️⃣ PHP Closure কী?
👉 Closure (Anonymous Function) হলো এমন একটি function যার কোনো নাম নেই, এবং এটাকে variable-এ assign করে ব্যবহার করা যায়।
📌 Basic Example:
$greet = function($name) {
return "Hello, $name";
};
echo $greet("Ruhul");
🔥 Closure এর বিশেষ ক্ষমতা (use keyword)
👉 বাইরের variable ভিতরে ব্যবহার করা যায়
$message = "Hi";
$greet = function($name) use ($message) {
return "$message, $name";
};
echo $greet("Sujon");
✔ use ($message) না দিলে কাজ করবে না
🚀 Laravel-এ Closure Example:
Route::get('/', function () {
return "Welcome";
});
👉 এখানে route-এর ভিতরের function টা closure
🎯 Closure কেন ব্যবহার করি?
- Callback function
- Route handling
- Collection method (
map, filter) - Clean & short code
🔹 2️⃣ PHP Magic Method কী?
👉 Magic Method হলো special method, যেগুলো automatically call হয় নির্দিষ্ট situation-এ।
👉 সব magic method শুরু হয় __ (double underscore) দিয়ে
🔥 Common Magic Methods
1️⃣ __construct() (Constructor)
class User {
public function __construct() {
echo "Object created";
}
}
👉 Object create হলে auto call হয়
2️⃣ __destruct()
public function __destruct() {
echo "Object destroyed";
}
3️⃣ __get() (Undefined property access)
class User {
public function __get($name) {
return "Property $name not found";
}
}
$user = new User();
echo $user->email;
4️⃣ __set() (Undefined property set)
public function __set($name, $value) {
echo "Setting $name = $value";
}
5️⃣ __call() (Undefined method call)
public function __call($method, $args) {
echo "Method $method not found";
}
6️⃣ __toString()
public function __toString() {
return "User object";
}
👉 Object print করলে call হয়
7️⃣ __invoke()
class Test {
public function __invoke() {
return "Called as function";
}
}
$obj = new Test();
echo $obj(); // invoke
🔍 Closure vs Magic Method
| বিষয় | Closure | Magic Method |
|---|---|---|
| কী | Anonymous function | Special class method |
| কাজ | Callback / inline logic | Auto-trigger behavior |
| Scope | Function level | Class level |
| Laravel usage | Route, Collection | Model, Eloquent |
🧠 Interview-ready Answer
👉 Closure:
Closure is an anonymous function that can capture variables from its parent scope using the
usekeyword.
👉 Magic Method:
Magic methods are special methods in PHP that are automatically invoked when certain actions occur, such as object creation, property access, or method calls.
🔥 Pro Insight (Impress Interviewer)
- Laravel heavily uses closures (route, middleware, collections)
- Eloquent uses magic methods (
__get,__set) for dynamic properties
প্রশ্ন ৯ ঃ laravel এ Macro & contract কি? কেন ব্যবহার করা হয়? কোন সিচুয়েশনে কোনটা ব্যবহার করবো? উদাহরণসহ ব্যাখ্যা করো? 1টা real Laravel project example (Macro + Contract একসাথে use করে দেখাও)
Answer:
🔹 Macro কী?
Laravel-এ Macro হলো runtime-এ কোনো existing class-এ নতুন method add করার উপায় (extend without modifying core class)।
👉 সাধারণত Facade বা utility class-এ use হয় (যেমন: Str, Collection, Response)
Example:
use Illuminate\Support\Str;
Str::macro('greet', function ($name) {
return "Hello, {$name}";
});
Str::greet('Ruhul'); // Hello, Ruhul
🔹 Contract কী?
Laravel-এ Contract মানে হলো interface
👉 এটা define করে “কি করতে হবে”, কিন্তু “কিভাবে করতে হবে” না
✔️ Implementation আলাদা class-এ থাকে
✔️ Loose coupling + testability বাড়ায়
Example:
interface PaymentContract {
public function pay($amount);
}
🔹 কেন ব্যবহার করি?
👉 Macro:
- Existing class modify না করে extend করতে
- Reusable helper method বানাতে
👉 Contract:
- Abstraction তৈরি করতে
- Easily implementation change করতে
- Clean architecture maintain করতে
🔥 কখন কোনটা ব্যবহার করবো?
| Situation | Use |
|---|---|
| Existing class extend করতে চাই | Macro |
| Multiple implementation পাগবে | Contract |
| Clean architecture দরকার | Contract |
| Helper method reuse করতে চাই | Macro |
🚀 Real Laravel Project Example (Macro + Contract Together)
ধরো তুমি একটা API response system বানাচ্ছো
🔹 Step 1: Contract (Response structure define)
interface ApiResponseContract {
public function success($data);
public function error($message);
}
🔹 Step 2: Implementation
class ApiResponseService implements ApiResponseContract {
public function success($data) {
return response()->json([
'status' => 'success',
'data' => $data
]);
}
public function error($message) {
return response()->json([
'status' => 'error',
'message' => $message
]);
}
}
🔹 Step 3: Service Provider Binding
$this->app->bind(
ApiResponseContract::class,
ApiResponseService::class
);
🔹 Step 4: Macro দিয়ে shortcut তৈরি
use Illuminate\Support\Facades\Response;
Response::macro('success', function ($data) {
return response()->json([
'status' => 'success',
'data' => $data
]);
});
🔹 Step 5: Controller-এ use
class UserController extends Controller
{
public function index(ApiResponseContract $response)
{
$users = User::all();
// Contract use
return $response->success($users);
// অথবা Macro use
// return response()->success($users);
}
}
🎯 Key Insight (Impress করার জন্য)
👉 Contract → architecture clean করে
👉 Macro → developer experience fast করে
✔️ একসাথে use করলে:
- Clean + Flexible + Developer-friendly system পাওয়া যায়
🎯 Short Interview Version:
"Macros allow us to dynamically extend existing Laravel classes with custom methods, while Contracts are interfaces that define abstraction and enable loose coupling. We use Macros for reusable helper methods and Contracts when we need flexible, swappable implementations. In real projects, Contracts handle core logic and Macros can provide convenient shortcuts for developers."
প্রশ্ন ১০ ঃ clousour & fn function কি? কেন ব্যবহার করা হয়? কোন সিচুয়েশনে কোনটা ব্যবহার করবো? উদাহরণসহ ব্যাখ্যা করো? 1টা real Laravel project example (clousour + fn function একসাথে use করে দেখাও)
Answer:
🔹 Closure কী?
PHP-তে Closure হলো anonymous function (নাম ছাড়া function)
👉 runtime-এ define করে variable-এর scope capture করতে পারে (use keyword দিয়ে)
Example:
$multiplier = 2;
$closure = function ($num) use ($multiplier) {
return $num * $multiplier;
};
echo $closure(5); // 10
🔹 fn function (Arrow Function) কী?
PHP 7.4+ এ introduce হয়েছে
👉 এটা short syntax closure
👉 automatically parent scope-এর variable capture করে (no use needed)
Example:
$multiplier = 2;
$fn = fn($num) => $num * $multiplier;
echo $fn(5); // 10
🔥 Key Difference
| বিষয় | Closure | fn (Arrow Function) |
|---|---|---|
| Syntax | বড় | ছোট (concise) |
| Scope capture |
use লাগে |
auto capture |
| Multiple statement | ✅ possible | ❌ only single expression |
| Readability | complex logic | simple logic |
🔹 কেন ব্যবহার করা হয়?
👉 Closure:
- Complex logic handle করতে
- Callback হিসেবে (routes, middleware, collections)
- যখন multiple line logic দরকার
👉 fn:
- ছোট, clean, readable code লিখতে
- Collection operations (map, filter, reduce)
- Simple transformation
🔹 কখন কোনটা ব্যবহার করবো?
| Situation | Use |
|---|---|
| Simple one-line logic | fn |
| Complex multi-line logic | Closure |
| Laravel collection chain | fn |
| Route / middleware complex handling | Closure |
🚀 Real Laravel Project Example (Closure + fn together)
ধরো তুমি user list API বানাচ্ছো 👇
Route::get('/users', function () {
$users = User::all();
// fn → simple transformation
$formatted = $users->map(
fn($user) => [
'name' => $user->name,
'email' => $user->email,
]
);
// Closure → complex filtering logic
$filtered = $formatted->filter(function ($user) {
if (str_contains($user['email'], '@gmail.com')) {
return true;
}
return false;
});
return response()->json($filtered->values());
});
🧠 Insight (Impress করার জন্য)
👉 fn = readability + clean code
👉 Closure = flexibility + power
✔️ দুটো একসাথে use করলে:
- Code clean থাকে
- Logic flexible থাকে
🎯 Short Interview Version:
"Closures are anonymous functions that can capture variables using the
usekeyword and are suitable for complex logic. Arrow functions (fn) are a shorter syntax with automatic variable capture and are ideal for simple one-line operations. In Laravel, we often usefnin collection methods for clean code and closures for more complex callbacks."
Top comments (0)