├── .gitignore
├── src
├── images
│ └── laravel_request_life_cycle.png
├── git.md
├── system-design.md
├── laravel.md
├── php.md
├── mysql.md
└── fundamentals.md
├── README.md
└── LICENSE
/.gitignore:
--------------------------------------------------------------------------------
1 | .idea/
--------------------------------------------------------------------------------
/src/images/laravel_request_life_cycle.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/ahmed-bermawy/backend-interview-questions/HEAD/src/images/laravel_request_life_cycle.png
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # Backend Interview Questions
2 | This repository contains a list of interview questions for backend developers.
3 |
4 | The questions are divided into categories:
5 |
6 | 1. [Fundamentals](https://github.com/ahmed-bermawy/backend-interview-questions/tree/main/src/fundamentals.md)
7 | 2. [PHP](https://github.com/ahmed-bermawy/backend-interview-questions/tree/main/src/php.md)
8 | 3. [Laravel](https://github.com/ahmed-bermawy/backend-interview-questions/tree/main/src/laravel.md)
9 | 4. [Mysql](https://github.com/ahmed-bermawy/backend-interview-questions/tree/main/src/mysql.md)
10 | 5. [Git](https://github.com/ahmed-bermawy/backend-interview-questions/tree/main/src/git.md)
11 | 6. [System Design](https://github.com/ahmed-bermawy/backend-interview-questions/tree/main/src/system-design.md)
12 |
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | MIT License
2 |
3 | Copyright (c) 2024 Ahmed Bermawy
4 |
5 | Permission is hereby granted, free of charge, to any person obtaining a copy
6 | of this software and associated documentation files (the "Software"), to deal
7 | in the Software without restriction, including without limitation the rights
8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9 | copies of the Software, and to permit persons to whom the Software is
10 | furnished to do so, subject to the following conditions:
11 |
12 | The above copyright notice and this permission notice shall be included in all
13 | copies or substantial portions of the Software.
14 |
15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21 | SOFTWARE.
22 |
--------------------------------------------------------------------------------
/src/git.md:
--------------------------------------------------------------------------------
1 | * ## What is the difference between git fetch and git pull?
2 | * `git fetch` downloads the changes from the remote repository but does not merge them with your local repository.
3 | * `git merge` merges the changes from the remote repository with your local repository.
4 | * `git pull` is a combination of `git fetch` and `git merge`.
5 |
6 | * ## What is the git rebase?
7 | `git rebase` is used to reapply commits on top of another base tip. It is used to maintain a linear project history.
8 |
9 | * ## What is the difference between git rebase and git merge?
10 | * `git rebase` rewrites the commit history by creating new commits for each commit in the original branch.
11 | * `git merge` merges the changes from one branch to another branch.
12 |
13 | * ## What is the git cherry-pick?
14 |
15 | `git cherry-pick` is used to apply a commit from one branch to another branch.
16 |
17 | * ## What is the git stash?
18 |
19 | `git stash` is used to save the changes in the working directory and index to a stack. It is used to switch to another branch without committing the changes.
20 |
21 | * ## What is the git bisect?
22 |
23 | `git bisect` is used to find the commit that introduced a bug by performing a binary search between two commits.
24 |
25 | * ## What is the git tag?
26 |
27 | `git tag` is used to create a tag for a specific commit. It is used to mark a specific commit in the repository.
28 |
29 | * ## What is the git blame?
30 |
31 | `git blame` is used to view the author and commit information for each line in a file. It shows the commit that last modified each line in the file.
32 |
33 | * ## What is the git log?
34 |
35 | `git log` is used to view the commit history of a repository. It shows the commit messages, authors, dates, and commit hashes.
36 |
37 | * ## What is the git reset?
38 |
39 | `git reset` is used to reset the current HEAD to a specific state. It is used to undo changes in the working directory and index.
40 |
41 | type of reset commands:
42 | * `git reset --soft` : Moves HEAD back to the specified commit, undo all the changes made between where HEAD was pointing and the specified commit.
43 | * `git reset --hard` : Reset the current branch to a previous commit, discarding any local changes and modifications made to the files.
44 |
45 |
--------------------------------------------------------------------------------
/src/system-design.md:
--------------------------------------------------------------------------------
1 | ## 🧩 System Overview
2 |
3 | A centralized system that records employee attendance through different check-in methods:
4 |
5 | * Normal login (username/password or punch button)
6 | * Wi-Fi–based clock-in (detects user near an approved router)
7 | * Face-match check-in (via camera & biometric match)
8 |
9 | ---
10 |
11 | ## ⚙️ Functional Requirements
12 | 1. User Management
13 | - Register, update, or deactivate employees.
14 | - Assign unique employee IDs and roles (admin, employee, HR).
15 |
16 | 2. Authentication & Authorization
17 | - Secure login (username/password).
18 | - Role-based access control for HR/admins.
19 |
20 | 3. Check-In / Check-Out Methods
21 | - Normal Check-in: User logs in via web/app.
22 | - Wi-Fi Check-in: System detects device connected to approved routers and auto-checks in.
23 | - Face-match Check-in: Capture image → run facial recognition → record attendance if matched.
24 |
25 | 4. Attendance Recording
26 | - Save timestamp, user ID, check-in type, device ID, and location.
27 | - Prevent duplicate check-ins within a time threshold.
28 |
29 | 5. Attendance Reporting
30 | - Daily/weekly/monthly reports per user or department.
31 | - Export to CSV/PDF.
32 |
33 | 6. Notifications
34 | - Notify user of successful check-in/out.
35 | - Alert admin if check-in attempts fail or unauthorized access is detected.
36 |
37 | 7. Admin Dashboard
38 | - View, filter, and edit attendance records.
39 | - Manage Wi-Fi routers and camera devices.
40 |
41 | ## 🧠 Non-Functional Requirements
42 |
43 | | Category | Description |
44 | | ------------------- | ------------------------------------------------------------------------------------ |
45 | | **Scalability** | System should support thousands of concurrent check-ins. |
46 | | **Availability** | 99.9% uptime using load-balanced servers and redundant DB. |
47 | | **Security** | Encrypted data (SSL/TLS), secure password storage (bcrypt), face data anonymization. |
48 | | **Performance** | Each check-in operation < 2 seconds (including face recognition). |
49 | | **Reliability** | Data integrity maintained even during network failures. |
50 | | **Maintainability** | Modular architecture (Microservices / SOA for check-in methods). |
51 | | **Auditability** | All actions logged for compliance and audits. |
52 | | **Usability** | Simple web and mobile UI for employees. |
53 | | **Compliance** | GDPR-compliant for biometric data handling. |
54 |
55 | ## 🏗️ High-Level Architecture
56 | 1. **Frontend**: (Web/Mobile App)
57 | - User interface for employees to check in/out.
58 | - Admin dashboard for HR and admins.
59 |
60 | 2. **Backend**: RESTful API
61 | 3. **Database**: Relational DB (e.g., PostgreSQL/MySQL)
62 | - Tables: Users, AttendanceRecords, WiFiRouters, Devices, Logs.
63 |
64 | 4. **Authentication Service**: OAuth2/JWT for secure login.
65 |
66 | 5. **Check-In Services**:
67 | - Normal Check-in Service
68 | - Wi-Fi Check-in Service (integrates with router APIs)
69 | - Face-Match Service (integrates with facial recognition API)
70 |
71 | 6. Redis for caching
72 | 7. API Gateway for routing requests
73 | 8. Message Queue (e.g., RabbitMQ) for async tasks (e.g., sending notifications, generating reports)
74 | 9. Notification Service (Email/SMS)
75 | 10. Logging & Monitoring (ELK Stack, Prometheus/Grafana)
76 | 11. Optional: LDAP or company SSO for user sync.
77 |
--------------------------------------------------------------------------------
/src/laravel.md:
--------------------------------------------------------------------------------
1 | * ## What is request life cycle in Laravel?
2 |
3 | The request life cycle in Laravel is the sequence of events that occur when a request is made to a Laravel application.
4 |
5 | 1. The request enters the application through the `public/index.php` file.
6 | 2. It loads all vendor files and the `bootstrap/app.php` file.
7 | 3. In `bootstrap/app.php` file determines request that is entering the application and sends it to the appropriate kernel is either the HTTP kernel or the console kernel also prepare Exception Handler.
8 | 4. Then passed to the `App\Http\Kernel` class, which loads the application's middleware.
9 | 5. Which will bootstrap the application and load service providers and needed configuration in `config/app.php` file.
10 | 6. Service providers are responsible for bootstrapping all the framework's various components, such as the database, queue, validation, and routing components.
11 | 7. Once the application has been bootstrapped and all service providers are registered and booted, the request will be handed over to the router for dispatching.
12 | 8. Once the route or controller method returns a response, the response will travel back outward through the route's middleware, giving the application a chance to modify or examine the outgoing response.
13 | 9. Finally, the response is then sent back to the client.
14 |
15 | during this life cycle, Laravel will load around 400 files.
16 |
17 |
18 |
19 |
20 | * ## What is the service container in Laravel?
21 |
22 | The Laravel service container is a powerful tool for managing class dependencies and performing dependency injection.
23 |
24 | It is a container that holds instances of classes and resolves dependencies automatically.
25 |
26 | * ## What is the service provider in Laravel?
27 |
28 | Service providers are the central place of all Laravel application bootstrapping.
29 |
30 | Your own application, as well as all of Laravel's core services, are bootstrapped via service providers.
31 |
32 | * ## What are jobs and when do we use them?
33 |
34 | Jobs in Laravel are used to handle asynchronous processing,
35 | allowing the application to perform time-consuming tasks
36 | (like sending emails, processing files, etc.) in the background without blocking the user interface.
37 | Jobs can be pushed onto different queues with varying priorities to be processed by queue workers.
38 |
39 |
40 | * ## What is CSRF?
41 | **Cross-Site Request Forgery** is a security feature
42 | used to prevent unauthorized actions on a website through forged HTTP requests.
43 | CSRF attacks occur
44 | when a malicious website tricks a user's browser
45 | into sending a request to a different website where the user is authenticated,
46 | without the user's knowledge or consent
47 | It is added by default to web in middleware group variable in Kernel.
48 |
49 | Also, you can find it in cookies under the name `XSRF-TOKEN`
50 |
51 | * ## What is Fillable Attribute in a Laravel model?
52 | It takes care of defining which fields are to be considered
53 | when the user inserts or updates data
54 |
55 | `$fillable` serves as a **white list** of attributes that should be mass assignable,
56 |
57 | The `$guarded` property should contain an array of attributes that you do not want to be mass assignable.
58 |
59 | All other attributes not in the array will be mass-assignable. So, $guarded functions like a **black list**
60 |
61 | * ## What is Middleware?
62 |
63 | Middleware is a mechanism that allows you to filter out HTTP requests entering your application.
64 |
65 | For example, Laravel includes a middleware that verifies your application's user is authenticated.
66 |
67 | If the user is not authenticated, the middleware will redirect the user to the login screen. However,
68 |
69 | if the user is authenticated, the middleware will allow the request to proceed further into the application.
70 |
71 | * ## What is Facades?
72 |
73 | Facades provide a "static" interface to classes that are available in the application's service container.
74 |
75 | * ## What is an Active Record?
76 |
77 | Active Record is a design pattern
78 | that links business objects and database tables
79 | to create a persistable domain model where the business object contains data retrieval,
80 | data storage, and data manipulation methods.
81 |
82 | * ## What are SQL Injections, how do you prevent them, and what are the best practices?
83 |
84 | SQL injection is a type of attack
85 | that occurs when an attacker inserts malicious SQL code into input fields or parameters in a web application's form,
86 | causing the application to execute unintended SQL commands.
87 | This can allow the attacker to access, modify, or delete data from the database
88 |
89 | To prevent SQL injection in Laravel:
90 | - Use Eloquent ORM or Query Builder: it automatically handles input sanitization and parameter binding, which helps prevent SQL injection.
91 | - Use Parameterized Queries: (->where('column', '=', $value)).
92 | - Avoid Raw Input in Queries: Never concatenate user input directly into your SQL queries. Always sanitize and validate user input before using it in database queries.
93 | - Use Validation: Validate user input using Laravel's validation rules (validate() method in controllers) to ensure that it meets your application's requirements before using it in database queries.
94 | - Escaping Input: If you must use raw input in queries use Laravel's DB::raw() method to escape the input properly.
95 | - Limit Database Privileges: Ensure that your database user account has the minimum necessary privileges required for your application. Avoid using accounts with full access to the database.
96 | - Use CSRF Protection: Cross-Site Request Forgery (CSRF) protection helps prevent malicious users from tricking authenticated users into executing unintended actions on your website.
97 | - Keep Laravel Updated: Keep your Laravel framework and its dependencies up to date to ensure that you have the latest security patches and features.
98 |
99 | Example for injection
100 |
101 | ```mysql
102 | SELECT * FROM users WHERE email = 'ahmed@bermawy.info'-- AND password = 'password';
103 |
104 | Username: admin'--
105 |
106 | `' OR '1'='1`
107 | SELECT * FROM users WHERE username = '' OR '1'='1' AND password = '' OR '1'='1'
108 |
109 | ```
110 |
111 | * ## What is the difference between soft delete and hard delete?
112 |
113 | Soft delete is a way to "delete" a record without actually removing it from the database.
114 |
115 | When a record is soft deleted, a `deleted_at` timestamp is set on the record, and the record is not returned in normal queries.
116 |
117 | Hard delete, on the other hand, is the actual removal of the record from the database.
118 |
119 | * ## retrieve both soft deleted and undeleted records from a database?
120 |
121 | You can use the `withTrashed()` method to retrieve both soft deleted and undeleted records from a database.
122 |
123 | ```php
124 | $posts = Post::withTrashed()->get();
125 | ```
126 |
127 | * ## What is the difference between has() and whereHas() in Laravel Eloquent?
128 |
129 | `has()` is used to filter the results based on the existence of a relationship.
130 |
131 | `whereHas()` is used to filter the results based on the existence of a relationship and the values of the related model.
132 |
133 | * ## What is the difference between first() and find() in Laravel Eloquent?
134 |
135 | `first()` returns the first record that matches the query conditions.
136 |
137 | `find()` returns a single record by its primary key.
138 |
139 | * ## What is the N+1 issue in Laravel and how do you solve it?
140 |
141 | The N+1 issue is a performance problem that occurs when you make N+1 queries to the database to retrieve related records.
142 |
143 | To solve the N+1 issue in Laravel, you can use eager loading with the `with()` method.
144 |
145 | ```php
146 | $posts = Post::with('comments')->get();
147 | ```
148 |
149 | * ## What is the difference between Eager Loading and Lazy Loading?
150 |
151 | Eager loading is the process of loading a model with its relationships at the time the model is queried.
152 |
153 | Lazy loading, on the other hand, is the process of loading the relationships only when they are accessed.
154 |
155 | example of eager loading
156 |
157 | ```php
158 | $posts = Post::with('comments')->get();
159 | ```
160 |
161 | example of lazy loading
162 |
163 | ```php
164 | $post = Post::find(1);
165 | $comments = $post->comments;
166 | ```
167 |
168 | * ## What is the difference between Factory and Seeder?
169 |
170 | A factory is used to define the structure of the data that will be inserted into the database.
171 |
172 | A seeder is used to populate the database with data using the factories.
173 |
174 | * ## What is the difference between a Repository and a Service?
175 |
176 | A repository is a class that abstracts the data layer and provides a clean API to interact with the database.
177 |
178 | A service is a class that encapsulates business logic and provides a clean API to interact with the application.
179 |
180 | * ## what is throttle in Laravel?
181 |
182 | Throttling is a way to limit the number of requests a user can make to a route within a specified time frame.
183 |
184 | It is used to prevent abuse of the application by limiting the number of requests a user can make.
185 |
186 |
187 |
188 | Example
189 |
190 | ```php
191 | Route::middleware('throttle:60,1')->get('/user', function () {
192 | return 'Hello World';
193 | });
194 | ```
195 |
196 |
197 |
198 | * ## What is Event and Listener in Laravel?
199 |
200 | Events are a way to notify other parts of the application that a certain action has occurred.
201 |
202 | Listeners are classes that handle the events and perform the necessary actions.
203 |
204 | example in laravel
205 |
206 | ```php
207 |
208 |
209 |
210 | * ## What is the difference between `auth()->user()` and `Auth::user()` in Laravel?
211 |
212 | `auth()->user()` is a helper function that returns the currently authenticated user.
213 |
214 | `Auth::user()` is a facade that provides access to the authentication services.
215 |
216 | * ## How to implement distributed locking in Laravel?
217 |
218 | Distributed locking is a way to prevent multiple processes from accessing a shared resource at the same time.
219 |
220 | In Laravel, you can use the `lockForUpdate()` method to implement distributed locking.
221 |
222 | ```php
223 | DB::table('posts')->where('id', 1)->lockForUpdate()->get();
224 | ```
225 |
226 | * ## How to implement builder or manager design pattern in Laravel?
227 |
228 |
229 |
230 | Example
231 |
232 | ```php
233 |
234 | interface ParserInterface
235 | {
236 | public function parse(string $path): array;
237 | }
238 |
239 | class ParserManager extends Manager
240 | {
241 |
242 | public function getDefaultDriver(): string
243 | {
244 | return 'json';
245 | }
246 |
247 | public function createJsonDriver(): JsonParser
248 | {
249 | return new JsonParser();
250 | }
251 |
252 | public function createCsvDriver(): CsvParser
253 | {
254 | return new CsvParser();
255 | }
256 | }
257 |
258 | class ParserServiceProvider extends ServiceProvider
259 | {
260 | public function register(): void
261 | {
262 | $this->app->singleton(ParserManager::class, function ($app) {
263 | return new ParserManager($app);
264 | });
265 |
266 | $this->app->alias(ParserManager::class, 'parser');
267 | }
268 | }
269 |
270 | class Parser extends Facade
271 | {
272 | protected static function getFacadeAccessor(): string
273 | {
274 | return 'parser';
275 | }
276 | }
277 |
278 |
279 | class CsvParser implements ParserInterface
280 | {
281 |
282 | public function parse(string $path): array
283 | {
284 | $file = fopen($path, 'r');
285 | $rows = [];
286 |
287 | while (($row = fgetcsv($file)) !== false) {
288 | $rows[] = $row;
289 | }
290 |
291 | fclose($file);
292 |
293 | return $rows;
294 | }
295 | }
296 |
297 | class JsonParser implements ParserInterface
298 | {
299 |
300 | public function parse(string $path): array
301 | {
302 | $json = file_get_contents($path);
303 | return json_decode($json, true);
304 | }
305 | }
306 |
307 | $jsonFile = storage_path('app/public/data.json');
308 | $data = Parser::parse($jsonFile); // because json is our default driver
309 |
310 | // to user csv driver
311 | $csvPath = storage_path('app/public/data.csv');
312 | $csvData = Parser::driver('csv')->parse($csvPath);
313 |
314 | ```
315 |
316 |
317 |
318 | * ## What are Accessors and Mutators?
319 |
320 | **Accessors** are used to format and retrieve attributes from models.
321 |
322 | **Mutators** are used to set or modify attribute values before saving to the database in Laravel models
323 |
324 | * ## How to test static method in Laravel?
325 |
326 |
327 |
328 | Example
329 |
330 | ```php
331 |
332 | class Math
333 | {
334 | public static function add(int $a, int $b): int
335 | {
336 | return $a + $b;
337 | }
338 | }
339 |
340 | class MathTest extends TestCase
341 | {
342 | public function testAdd()
343 | {
344 | $mockMath = Mockery::mock(Math::class);
345 | $mockMath->shouldReceive('add')->andReturn(5);
346 | }
347 | }
348 | ```
349 |
350 |
351 |
352 | * ## How to handle failed jobs in Laravel?
353 |
354 | You can use the `failed()` method on the job class to handle failed jobs in Laravel.
355 |
356 | ```php
357 |
358 | class ProcessPodcast implements ShouldQueue
359 | {
360 | use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;
361 |
362 | public function handle()
363 | {
364 | throw new Exception('This job has failed!');
365 | }
366 |
367 | public function failed(Exception $exception)
368 | {
369 | // Send user notification of failure, etc...
370 | }
371 | }
372 |
373 | ```
374 |
375 |
--------------------------------------------------------------------------------
/src/php.md:
--------------------------------------------------------------------------------
1 | * ## What is PSR?
2 | PHP Standards Recommendations (PSR) are a set of standards that PHP developers should follow to write clean, readable, and maintainable code
3 | like:
4 |
5 | 1. psr-3 responsible for logging.
6 | 2. psr-4 responsible for autoloading classes.
7 | 3. psr-6 responsible for caching.
8 | 4. psr-12 responsible for coding style guide.
9 |
10 | * ## What is Composer?
11 | Composer is a dependency manager for PHP. It allows you to declare the libraries your project depends on and it will manage (install/update) them for you.
12 |
13 | * ## What is the difference between require and require_once?
14 | `require` and `require_once` are both used to include a file in the current script.
15 | The difference is that `require_once` will check if the file has already been included and if so, it will not include it again.
16 |
17 | * ## What is the difference between var_dump and print_r?
18 | `var_dump` displays structured information about one or more expressions that includes its type and value.
19 |
20 | `print_r` displays information about a variable in a way that's readable by humans.
21 |
22 | * ## What is the difference between == and ===?
23 | `==` is an equality operator that compares two values and returns `true` if they are equal.
24 |
25 | `===` is an identity operator that compares two values and returns `true` if they are equal and of the same type.
26 |
27 | * ## Does PHP support multiple inheritance?
28 | No. PHP only supports multi-level inheritance.
29 |
30 | example to illustrate the difference between multiple and multi-level inheritance in PHP:
31 |
32 |
33 |
34 | Multiple Inheritance (Not Supported in PHP)
35 |
36 | ```php
37 | // Parent Class 1
38 | class ParentClass1 {
39 | public function method1() {
40 | return "Method 1 from ParentClass1";
41 | }
42 | }
43 |
44 | // Parent Class 2
45 | class ParentClass2 {
46 | public function method2() {
47 | return "Method 2 from ParentClass2";
48 | }
49 | }
50 |
51 | // Child Class attempting to use multiple inheritance
52 | // This will result in a syntax error in PHP
53 | class ChildClass extends ParentClass1, ParentClass2 {
54 | // Class body
55 | }
56 | ```
57 |
58 |
59 |
60 |
61 | Multi-level Inheritance (Supported in PHP)
62 |
63 | ```php
64 | // Grandparent Class
65 | class GrandparentClass {
66 | public function method1() {
67 | return "Method 1 from GrandparentClass";
68 | }
69 | }
70 |
71 | // Parent Class inheriting from GrandparentClass
72 | class ParentClass extends GrandparentClass {
73 | public function method2() {
74 | return "Method 2 from ParentClass";
75 | }
76 | }
77 |
78 | // Child Class inheriting from ParentClass
79 | class ChildClass extends ParentClass {
80 | // Class body
81 | }
82 |
83 | // Create an instance of ChildClass
84 | $childObj = new ChildClass();
85 |
86 | // Access methods from GrandparentClass and ParentClass
87 | echo $childObj->method1(); // Output: Method 1 from GrandparentClass
88 | echo $childObj->method2(); // Output: Method 2 from ParentClass
89 | ```
90 |
91 |
92 | * ## Is HTTP protocol stateless or stateful?
93 | HTTP (HyperText Transfer Protocol) is a stateless protocol. This means that each request is independent and unrelated to the previous or subsequent requests.
94 |
95 | * ## What is a session?
96 | A session is a way to store information (in variables) to be used across multiple pages. By default, session variables last until the user closes the browser.
97 |
98 | * ## What is a cookie?
99 | A cookie is a small piece of data that is stored on the user's computer by the web browser while browsing a website. Cookies are used to remember stateful information or to track user activity.
100 |
101 | * ## What is more secure session or cookie? and why?
102 | Sessions are generally considered more secure than cookies because the session data is stored on the server and not on the client's computer.
103 |
104 | also session is encrypted by default, while cookies can be encrypted but it's not the default behavior.
105 |
106 | * ## How does the server read the session or cookies from the user browser?
107 | The server reads the session data from the user's browser by using a session ID. The session ID is stored in a cookie or passed as a URL parameter. The server uses this session ID to retrieve the session data stored on the server.
108 |
109 | * ## What is the difference between class and interface?
110 | 1. Interfaces do not contain business logic
111 | 2. You must extend the interface to use.
112 | 3. You can't create an object of the interface.
113 |
114 | * ## What is a Scope Resolution Operator?
115 | The Scope Resolution Operator `::` is used to access class constants or static properties and methods.
116 |
117 | * ## What are Static properties?
118 | Static properties cannot be accessed through the object using the arrow operator `->`.
119 |
120 | Declaring class properties or methods as static makes them accessible without needing an instantiation of class
121 |
122 | * ## What are Magic Methods?
123 | Magic methods are special methods built into PHP that are called automatically when certain conditions are met like
124 |
125 | `__construct`, `__destruct`, `__get`, `__set`, `__isset`, `__unset`, `__call`, `__callStatic`, `__toString`, `__invoke`, `__set_state`, `__clone`, `__sleep`, `__wakeup`, `__serialize`, `__unserialize`, `__debugInfo`.
126 |
127 | * ## What’s the difference between unset() and unlink()?
128 | `unset()` used to unset a variable.
129 |
130 | `unlink()` used to delete a file from the file system.
131 |
132 | * ## How can we get the number of elements in an array?
133 | You can use the `count()` function to get the number of elements in an array.
134 |
135 | * ## What is the difference between $_GET and $_POST?
136 | `$_GET` is an associative array of variables passed to the current script via the URL parameters.
137 |
138 | `$_POST` is an associative array of variables passed to the current script via the HTTP POST method.
139 |
140 | * ## How to check if two objects are extended from the same parent or class?
141 | You can use the `instanceof` operator.
142 |
143 | * ## Overriding vs Overloading?
144 | Overriding is when a child's class redefines a method from the parent class.
145 |
146 | Overloading is when a single method behaves differently based on the number or type of arguments passed to it.
147 |
148 | * ## Does PHP support Overloading?
149 | No, PHP does not support method overloading.
150 |
151 | if you try to define two methods with the same name in a class. you will have a fatal error.
152 |
153 |
154 |
155 | Not Supported Overloading
156 |
157 | ```php
158 |
159 | class SampleClass
160 | {
161 | function add(int $a, int $b): int
162 | {
163 | return $a + $b;
164 | }
165 |
166 | function add(int $a, int $b, int $c): int
167 | {
168 | return $a + $b + $c > 10 ?? 10;
169 | }
170 | }
171 |
172 | // Fatal error: Cannot redeclare SampleClass::add()
173 |
174 | ```
175 |
176 |
177 | you can use `func_get_args()` to get all arguments passed to a function.
178 |
179 | You can only overload methods using the magic method __call
180 |
181 |
182 |
183 | Example of using the magic method __call
184 |
185 | ```php
186 | class SampleClass
187 | {
188 | function __call($name, $arguments)
189 | {
190 | if ($name == 'add') {
191 | if (count($arguments) == 2) {
192 | return $this->addTwo(...$arguments);
193 | } elseif (count($arguments) == 3) {
194 | return $this->addThree(...$arguments);
195 | }
196 | }
197 | }
198 |
199 | function addTwo(int $a, int $b): int
200 | {
201 | return $a + $b;
202 | }
203 |
204 | function addThree(int $a, int $b, int $c): int
205 | {
206 | return $a + $b + $c > 10 ?? 10;
207 | }
208 | }
209 |
210 | $sample = new SampleClass();
211 |
212 | echo $sample->add(1, 2); // Output: 3
213 | echo $sample->add(1, 2, 3); // Output: 6
214 | ```
215 |
216 |
217 |
218 | * ## What is PHP Trait?
219 | A Trait is simply a group of methods that you want to include within another class.
220 | A Trait, like an abstract class, cannot be instantiated on its own.
221 | The main benefit of traits is their reusable nature.
222 | The PHP language is a single inheritance language
223 |
224 |
225 |
226 | Example
227 |
228 | ```php
229 | trait SharePost {
230 | public function share($item)
231 | {
232 | return 'share this post;
233 | }
234 | }
235 |
236 | class Post {
237 | use SharePost;
238 | }
239 |
240 | $post = new Post();
241 |
242 | echo $post->share('post'); // Output: share this post
243 | ```
244 |
245 |
246 |
247 | * ## What is the Design pattern?
248 | A general repeatable solution to a commonly occurring problem in software design.
249 |
250 | * ## What is the difference between pass-by-value and pass-by-reference?
251 | Pass by value means that a copy of the variable is passed to the function,
252 |
253 | while pass by reference means that the actual variable is passed to the function.
254 | it is kind of made it has global variable if you change anything in the pass by reference,
255 | so you are changing it outside the function scope
256 |
257 | Also, if you pass an object as a variable, this is pass by reference
258 |
259 |
260 |
261 | Pass by value
262 |
263 | ```php
264 | function printString($string) {
265 | $string = "This is pass by value"."\n";
266 |
267 | print($string);
268 | }
269 |
270 | $string = "Global Value"."\n";
271 | printString($string);
272 | print($string);
273 |
274 | // Output:
275 | // This is pass by value
276 | // Global Value
277 |
278 | ```
279 |
280 |
281 |
282 |
283 |
284 | Pass by reference
285 |
286 | ```php
287 | function printString(&$string) {
288 | $string = "This is pass by reference"."\n";
289 |
290 | print($string);
291 | }
292 |
293 | $string = "Global Value"."\n";
294 |
295 | printString($string);
296 | print($string);
297 |
298 | // Output:
299 | // This is pass by reference
300 | // This is pass by reference
301 |
302 | ```
303 |
304 |
305 |
306 | * ## How to catch any exception in PHP?
307 | You can use the `throwable` interface to catch any exception in PHP.
308 |
309 | * Throwable
310 | * Error
311 | * Exception
312 |
313 |
314 |
315 | Example
316 |
317 | ```php
318 | try {
319 | // Code that may throw an exception
320 | } catch (Throwable $e) {
321 | // Catch any exception
322 | echo 'Caught exception: ', $e->getMessage(), "\n";
323 | }
324 | ```
325 |
326 |
327 |
328 | * ## What is arrow function in PHP?
329 | Arrow functions are a more concise way of writing anonymous functions in PHP.
330 |
331 |
332 |
333 | Example
334 |
335 | ```php
336 | $numbers = [1, 2, 3, 4, 5];
337 |
338 | // Using traditional anonymous function
339 | $filtered = array_filter($numbers, function ($num) {
340 | return $num % 2 === 0;
341 | });
342 |
343 | // Using arrow function
344 | $filtered = array_filter($numbers, fn($num) => $num % 2 === 0);
345 | ```
346 |
347 |
348 |
349 | * ## Give me example of match expression in PHP?
350 |
351 | Match expression is a more concise and readable way to compare a value against many different values in PHP.
352 |
353 |
354 |
355 | Example
356 |
357 | ```php
358 | $day = 'Monday';
359 |
360 | // Using traditional switch statement
361 | switch ($day) {
362 | case 'Monday':
363 | echo 'Start of the week';
364 | break;
365 | case 'Friday':
366 | echo 'End of the week';
367 | break;
368 | default:
369 | echo 'Middle of the week';
370 | }
371 |
372 | // Using match expression
373 | echo match ($day) {
374 | 'Monday' => 'Start of the week',
375 | 'Friday' => 'End of the week',
376 | default => 'Middle of the week',
377 | };
378 | ```
379 |
380 |
381 |
382 | * ## Is match faster than switch in PHP?
383 |
384 | Yes, match is faster than switch in PHP
385 | because match is a more optimized and concise way to compare a value against many different values.
386 |
387 | * ## can we define properties in interfaces in PHP?
388 |
389 | Yes, you can define properties in interfaces in PHP.
390 |
391 |
392 |
393 |
394 | Example
395 |
396 | ```php
397 | interface SampleInterface
398 | {
399 | public const NAME = 'John Doe';
400 | }
401 |
402 | echo SampleInterface::NAME; // Output: John Doe
403 | ```
404 |
405 |
406 |
407 | * ## How to test static method in PHPUnit mocking?
408 |
409 | You can use the `setStaticExpectations` method in PHPUnit to test static methods.
410 |
411 |
412 |
413 | Example
414 |
415 | ```php
416 | class SampleClass
417 | {
418 | public static function add(int $a, int $b): int
419 | {
420 | return $a + $b;
421 | }
422 | }
423 |
424 | class SampleTest extends TestCase
425 | {
426 | public function testAdd()
427 | {
428 | $this->staticExpects(SampleClass::class)
429 | ->method('add')
430 | ->with(1, 2)
431 | ->willReturn(3);
432 |
433 | $result = SampleClass::add(1, 2);
434 |
435 | $this->assertEquals(3, $result);
436 | }
437 | }
438 | ```
439 |
440 |
441 |
442 | * ## you have a bug on production and you have access to database and logs, how do you debug it?
443 |
444 | 1. Check the logs for any error messages or exceptions.
445 | 2. Check the database for any incorrect data or missing records.
446 | 3. Use debugging tools like Xdebug to step through the code and identify the issue.
447 | 4. Use print statements to log the values of variables and functions to identify the issue.
448 | 5. Use profiling tools like Blackfire to identify performance bottlenecks.
449 | 6. Use monitoring tools like New Relic to identify any performance issues.
450 | 7. Use version control to identify any recent changes that may have caused the bug.
451 | 8. Use error tracking tools like Sentry to identify and track errors in production.
452 |
--------------------------------------------------------------------------------
/src/mysql.md:
--------------------------------------------------------------------------------
1 | * ## Is the Mysql query case-sensitive?
2 |
3 | By default, MySQL queries are not case-sensitive. However, this behavior can be changed by setting the `lower_case_table_names` system variable.
4 |
5 |
6 | Example
7 |
8 | ```sql
9 | SELECT VERSION(), CURRENT_DATE;
10 | SeLect version(), current_date;
11 | seleCt vErSiOn(), current_DATE;
12 | ```
13 |
14 |
15 | * ## What is the difference between CHAR and VARCHAR?
16 | `CHAR` and `VARCHAR` are both used to store string data in MySQL.
17 |
18 | `CHAR` stores fixed-length strings and `VARCHAR` stores variable-length strings.
19 |
20 | * ## What are the main differences between InnoDB and MyISAM?
21 | InnoDB supports transactions, foreign keys and relationship constraints, while MyISAM does not.
22 |
23 | InnoDB has row-level locking, while MyISAM only supports table-level locking.
24 |
25 | InnoDB has better crash recovery capabilities compared to MyISAM.
26 |
27 | * ## What is the difference between the LIKE and REGEXP operators?
28 |
29 | `LIKE` is used to match patterns using wildcards `%`
30 |
31 | while `REGEXP` is used to match patterns using regular expressions `^`.
32 |
33 |
34 | Example
35 |
36 | ```sql
37 | SELECT * FROM users WHERE name LIKE 'A%'; -- Matches names starting with 'A'
38 |
39 | SELECT * FROM users WHERE name REGEXP '^A'; -- Matches names starting with 'A'
40 | ```
41 |
42 |
43 | * ## What is database Normalization?
44 | Database normalization is the process
45 | of organizing the columns and tables of a relational database
46 |
47 | to minimize redundancy and dependency
48 | by dividing large tables into smaller tables and defining relationships between them.
49 |
50 | * ## Can unique column have default in mysql?
51 |
52 | Yes, a unique column can have a default value in MySQL.
53 | However, the default value must be unique for each row in the table.
54 | If you try to insert a row with a default value that already exists in the unique column,
55 | MySQL will return an error.
56 |
57 | ```
58 | CREATE TABLE users (
59 | id INT AUTO_INCREMENT PRIMARY KEY,
60 | email VARCHAR(255) UNIQUE DEFAULT NULL
61 | );
62 | ```
63 | Here, email is UNIQUE and has a default value of NULL.
64 |
65 | This works fine because null is not considered equal to another null text, so multiple rows can have null in a unique column.
66 |
67 | you can also set a specific default value as long as it is unique.
68 | ```
69 | CREATE TABLE users (
70 | id INT AUTO_INCREMENT PRIMARY KEY,
71 | email VARCHAR(255) UNIQUE NULL DEFAULT 1
72 | );
73 | ```
74 |
75 | in this case , the first row inserted without an email will have the default value of 1,
76 |
77 | but the second row inserted without an email will cause a duplicate entry error.
78 |
79 | So you can only have one row with the default value of 1 in the email column.
80 |
81 |
82 | * ## What are the TRIGGERS in MySQL?
83 | A trigger is a set of actions that are run automatically when a specified change operation
84 | (SQL INSERT, UPDATE, or DELETE statement) is performed on a specified table
85 |
86 | The following TRIGGERS are allowed in MySQL:
87 |
88 | BEFORE INSERT
89 | AFTER INSERT
90 | BEFORE UPDATE
91 | AFTER UPDATE
92 | BEFORE DELETE
93 | AFTER DELETE
94 |
95 | * ## What is the transaction?
96 | A transaction is a unit of work that you want to treat as "a whole." It has to either happen in full or not at all.
97 |
98 |
99 | * ## What is the ACID property in a database?
100 | ACID (Atomicity, Consistency, Isolation, Durability)
101 | is a set of properties that guarantee that database transactions are processed reliably.
102 |
103 | - **Atomicity:** All changes to data are performed as if they are a single operation.
104 | - **Consistency:** the change can only happen if the new state of the system is valid; any attempt to commit an invalid change will fail, leaving the system in its previous valid state.
105 | - **Isolation:** Transactions are isolated from each other until they are completed.
106 | - **Durability:** Changes made by completed transactions are saved to disk and are not lost in case of a system failure.
107 |
108 |
109 | Example
110 |
111 | ```sql
112 | START TRANSACTION;
113 |
114 | INSERT INTO users (name, email) VALUES ('John Doe', 'john_doe@example.com');
115 |
116 | COMMIT;
117 | ```
118 |
119 |
120 | * ## What is the deadlock in MySQL? and how to prevent it?
121 |
122 | A deadlock in MySQL occurs when two or more transactions are waiting for each other to release locks on resources, resulting in a situation where none of the transactions can proceed.
123 |
124 | To prevent deadlocks in MySQL, you can follow these best practices:
125 | - Access tables and rows in a consistent order across all transactions.
126 | - Keep transactions short and avoid long-running transactions.
127 | - Pessimistic locking Use explicit locking (e.g., SELECT ... FOR UPDATE) to control the order of resource acquisition, use lockForUpdate in Laravel
128 | - Optimistic locking Use versioning or timestamps to detect and handle conflicts without locking resources.
129 |
130 | * ## How to represent boolean values in MySQL?
131 | In MySQL, boolean values are represented using a `BOOLEAN` or `BOOL` data type, which are aliases for `TINYINT(1)`.
132 |
133 | also you can use `ENUM` instead of `BOOLEAN` to represent boolean values in MySQL
134 |
135 | * ## Select from categories that have more than five products?
136 | ```sql
137 | SELECT category_id, COUNT(product_id) as total_products
138 | FROM products
139 | GROUP BY category_id
140 | HAVING total_products > 5;
141 | ```
142 |
143 | * ## What is the difference between the WHERE and HAVING clauses?
144 |
145 | `WHERE` is used to filter rows before any groupings are made.
146 |
147 | while `HAVING` is used to filter rows after groupings are made, also `HAVING` is used with `GROUP BY` clause.
148 |
149 |
150 | * ## How to select only unique values from a column?
151 |
152 | You can use the `DISTINCT` keyword to select only unique values from a column.
153 |
154 | ```sql
155 | SELECT DISTINCT product_name FROM products;
156 | ```
157 |
158 | * ## What are the database transaction logs?
159 |
160 | A database's transaction log is a file or set of files that record all the changes made to the data in the database. It is an essential component of database management systems (DBMS) that ensures data integrity and provides the ability to recover from failures.
161 | The transaction log serves several key purposes:
162 |
163 | **Recovery:** The transaction log allows the database to recover to a consistent state in the event of a system failure, such as a power outage or hardware failure. By replaying the transactions recorded in the log, the database can restore the data to its state before the failure occurred.
164 |
165 | **Rollback:** The transaction log allows transactions to be rolled back or undone. If a transaction is not completed successfully, the database can use the transaction log to reverse the changes made by the transaction and restore the data to its original state.
166 |
167 | **Concurrency Control:** The transaction log is used to support concurrency control mechanisms, such as locking and multiversion concurrency control (MVCC). These mechanisms ensure that multiple transactions can access and modify the same data without conflicting with each other.
168 |
169 | **Replication:** In some database systems, the transaction log is used to replicate changes to other databases or servers. By replaying the transactions from the log, the replication process can keep multiple databases in sync.
170 |
171 | * ## What is the difference between the delete and truncate command?
172 |
173 | `DELETE` is a DML (Data Manipulation Language) statement.
174 | It is used to remove specific rows from a table based on a condition.
175 |
176 | When you use DELETE, the operation is logged in the database's transaction log, which means you can use the ROLLBACK command to undo the operation.
177 |
178 | DELETE is slower than TRUNCATE, especially for large tables, because it generates a separate entry in the transaction log for each deleted row.
179 | Example:
180 | ```sql
181 | DELETE FROM table_name WHERE condition;
182 | ```
183 |
184 | `TRUNCATE` is a DDL (Data Definition Language) statement.
185 | It is used to remove all rows from a table, but it does not delete the table structure (columns, constraints, indexes, etc.).
186 |
187 | TRUNCATE is faster than DELETE, especially for large tables, because it does not generate individual delete entries in the transaction log. Instead, it deallocates the data pages and resets any auto-increment counters.
188 |
189 | TRUNCATE cannot be rolled back, and it resets the table's auto-increment counter.
190 | Example:
191 | ```sql
192 | TRUNCATE TABLE table_name;
193 | ```
194 |
195 | * ## Why truncate make the table autoincrement to 1?
196 |
197 | This behavior is by design and is intended to ensure
198 | that the auto-increment column starts from the beginning when new rows are inserted into the table after truncation.
199 |
200 | * ## What is the difference between Union and Union All?
201 |
202 | `UNION` and `UNION ALL` are used to combine the result sets of two or more SELECT statements.
203 |
204 | `UNION` removes duplicate rows from the combined result set, while `UNION ALL` includes all rows, including duplicates.
205 |
206 | `UNION` is slower than `UNION ALL` because it has to perform an additional step to remove duplicates.
207 |
208 | * ## What about stored procedures?
209 |
210 | A stored procedure in MySQL is a prepared SQL code that you can save, reuse, and share with others. Stored procedures allow you to group a set of SQL statements into a single unit and execute them whenever needed, without having to rewrite the code each time. Stored procedures can also accept parameters, making them more flexible and reusable.
211 |
212 | Here's a basic example of how to create a stored procedure in MySQL:
213 | ```sql
214 | CREATE PROCEDURE sp_get_employee(IN employee_id INT)
215 | BEGIN
216 | SELECT * FROM employees WHERE id = employee_id;
217 | END;
218 | ```
219 | In this example, sp_get_employee is the name of the stored procedure, and it accepts one input parameter employee_id. The BEGIN and END keywords enclose the body of the stored procedure, which consists of a single SELECT statement that retrieves the employee record with the specified ID.
220 |
221 | Once you've created a stored procedure, you can call it like this:
222 |
223 | `CALL sp_get_employee(1);`
224 |
225 | * ## What about function?
226 |
227 | A function in MySQL is a set of SQL statements that can be reused in other SQL statements or stored procedures. Functions can accept parameters, perform calculations or data manipulations, and return a value. Functions are similar to stored procedures, but they are typically used to perform specific calculations or data transformations rather than executing a sequence of SQL statements.
228 |
229 | Here's a basic example of how to create a function in MySQL:
230 | ```sql
231 | CREATE FUNCTION calculate_tax(amount DECIMAL(10,2)) RETURNS DECIMAL(10,2)
232 | BEGIN
233 | DECLARE tax DECIMAL(10,2);
234 | SET tax = amount * 0.1;
235 | RETURN tax;
236 | END;
237 | ```
238 |
239 | * ## What is the difference between a stored procedure and a function?
240 |
241 | Stored procedures and functions are both reusable blocks of SQL code
242 | that can be called from other SQL statements or applications.
243 | However, there are some key differences between the two:
244 |
245 | **Return Value:** Functions must return a value, while stored procedures do not have to return a value.
246 |
247 | **Usage:** Functions are typically used to perform calculations or data transformations and return a single value, while stored procedures are used to execute a sequence of SQL statements and perform more complex operations.
248 |
249 | **Transaction Control:** Stored procedures can control transactions using COMMIT and ROLLBACK statements, while functions cannot.
250 |
251 | **Error Handling:** Stored procedures can handle errors using the DECLARE HANDLER statement, while functions cannot.
252 |
253 | **Scope:** Functions can be called from SQL statements, stored procedures, and other functions, while stored procedures can only be called from SQL statements or other stored procedures.
254 |
255 |
256 | * ## What is the view in the database?
257 |
258 | A view in a database is a virtual table that is based on the result set of a SELECT statement. Views allow you to simplify complex queries by storing them as a virtual table that can be queried like a regular table. Views do not store any data themselves; they simply provide a way to present data from one or more tables in a structured format.
259 | Views have several advantages:
260 |
261 | **Simplicity:** Views allow you to encapsulate complex queries into a single, easy-to-use object.
262 |
263 | **Security:** Views can restrict access to certain columns or rows of a table, allowing you to control the data that users can see.
264 |
265 | **Performance:** Views can improve performance by precomputing expensive queries and storing the results.
266 |
267 | **Data Integrity:** Views can ensure that certain constraints are always enforced, such as ensuring that only certain rows are visible or that certain calculations are always correct.
268 |
269 |
270 |
271 | Example
272 |
273 | ```sql
274 | -- To create view
275 | CREATE VIEW high_salary_employees AS
276 | SELECT name
277 | FROM employees
278 | WHERE salary > 50000;
279 |
280 | -- Call the view
281 | SELECT * FROM high_salary_employees;
282 |
283 | -- Drop view
284 | DROP VIEW view_name;
285 | ```
286 |
287 |
288 |
289 | * ## How to analysis slow query in MySQL?
290 |
291 | MySQL provides several tools for analyzing slow queries and optimizing database performance. Some of the most common tools include:
292 |
293 | **EXPLAIN:** The EXPLAIN statement can be used to analyze the execution plan of a query and identify potential performance issues, such as missing indexes or inefficient joins.
294 |
295 | you can see all indexes in `possible_keys` column
296 |
297 | ```sql
298 | EXPLAIN SELECT * FROM employees WHERE salary > 50000;
299 | ```
300 |
301 | **Partitioning:** Split large tables into smaller. Partitioning can improve query performance by reducing the amount of data that needs to be scanned for each query.
302 |
303 | ```sql
304 |
305 | CREATE TABLE employees (
306 | id INT,
307 | name VARCHAR(50),
308 | salary INT
309 | )
310 | PARTITION BY RANGE (salary) (
311 | PARTITION p0 VALUES LESS THAN (50000),
312 | PARTITION p1 VALUES LESS THAN (100000),
313 | PARTITION p2 VALUES LESS THAN (MAXVALUE)
314 | );
315 | ```
316 |
317 |
318 | **SHOW PROFILE:** The SHOW PROFILE statement can be used to display detailed information about the execution of a query, including the time spent in each stage of the query execution.
319 |
320 | ```sql
321 | SET profiling = 1;
322 | SELECT * FROM employees WHERE salary > 50000;
323 | SHOW PROFILE;
324 | ```
325 |
326 | **MySQL Performance Schema:** The Performance Schema is a feature in MySQL that provides detailed performance metrics about the database server, including information about query execution, resource usage, and locking.
327 |
328 | ```sql
329 | SELECT * FROM performance_schema.events_statements_summary_by_digest;
330 | ```
331 |
332 | **MySQL Query Analyzer:** The MySQL Query Analyzer is a graphical tool that can be used to analyze slow queries, identify performance bottlenecks, and optimize database performance.
333 |
334 | * ## What are the aggregation functions in MySQL?
335 |
336 | Aggregation functions in MySQL are functions that operate on a set of values and return a single value as a result.
337 |
338 |
339 |
340 | Common aggregation functions in MySQL
341 |
342 | **COUNT:** Returns the number of rows that match a specified condition.
343 |
344 | ```sql
345 | SELECT COUNT(*) FROM employees;
346 | ```
347 |
348 | **SUM:** Returns the sum of a set of values.
349 |
350 | ```sql
351 | SELECT SUM(salary) FROM employees;
352 | ```
353 |
354 | **AVG:** Returns the average of a set of values.
355 |
356 | ```sql
357 | SELECT AVG(salary) FROM employees;
358 | ```
359 |
360 | **MIN:** Returns the minimum value in a set of values.
361 |
362 | ```sql
363 | SELECT MIN(salary) FROM employees;
364 | ```
365 |
366 | **MAX:** Returns the maximum value in a set of values.
367 |
368 | ```sql
369 | SELECT MAX(salary) FROM employees;
370 | ```
371 |
372 |
373 |
374 | * ## If I want to write-only to a database, what is better engine for that?
375 |
376 | If you want too write-only to a database, the best storage engine for that purpose is `MyISAM`.
377 |
378 | MyISAM is a non-transactional storage engine optimized for write-heavy workloads.
379 | It is designed for high-speed inserts and updates
380 | and is well-suited for applications that require fast write performance
381 |
382 | * ## How indexing works in MySQL?
383 |
384 | Indexing in MySQL is a way to optimize the performance of queries
385 | by reducing the number of rows that need to be scanned to retrieve the desired data.
386 | An index is a data structure that stores the values of one or more columns in a table in a sorted order,
387 | allowing the database to quickly locate the rows that match a given condition.
388 |
389 | * ## Can you add unique index to a column that has duplicate values?
390 |
391 | No, you cannot add a unique index to a column that has duplicate values.
392 |
393 | A unique index enforces the constraint that all values in the indexed column(s) must be unique,
394 |
395 | * ## Can you add a unique index to a column that has data?
396 |
397 | Yes, you can add a unique index to a column that already has data.
398 |
399 | When you add a unique index to a column that already has data,
400 | the database will check the existing data to ensure that there are no duplicate values in the column.
401 |
402 | If the column contains duplicate values,
403 | the database will prevent you from adding the unique index until you resolve the duplicates.
404 |
405 | * ## What happens to the existing index on the 'first_name' column when I add a composite index for 'first_name' and 'last_name'?
406 |
407 | The existing individual indexes on the columns will still exist,
408 | but they will not be used by the database optimizer when querying both columns together.
409 |
410 | The database optimizer will use the new composite index to optimize queries that involve both columns.
411 |
412 | * ## should we delete the old index?
413 |
414 | It is recommended to do so to avoid confusion and unnecessary overhead.
415 |
416 | * ## You have given api, and it has taken extra time around 20 seconds, and you reach to query level how you will speed it up?
417 |
418 | There are several ways to speed up a slow API query in MySQL:
419 |
420 | **Optimize the Query:** Review the query execution plan using the EXPLAIN statement and identify any potential performance bottlenecks, such as missing indexes or inefficient joins. Make sure that the query is using the appropriate indexes and that the tables are properly optimized.
421 |
422 | **Add Indexes:** Add indexes to the columns used in the WHERE, JOIN, and ORDER BY clauses of the query to speed up data retrieval. Be careful not to add too many indexes, as this can slow down write operations.
423 |
424 | **Partitioning:** Partition large tables into smaller partitions based on a range of values, such as dates or IDs. Partitioning can improve query performance by reducing the amount of data that needs to be scanned for each query.
425 |
426 | **Caching:** Implement caching mechanisms to store the results of frequently executed queries in memory. This can reduce the load on the database server and speed up query execution.
427 |
428 | **Query Optimization:** Rewrite the query to use more efficient SQL constructs, such as subqueries, joins, and aggregate functions. Avoid using SELECT * and limit the number of columns returned by the query.
429 |
430 | **Database Configuration:** Review the MySQL server configuration settings, such as buffer sizes, cache settings, and thread pool settings. Make sure that the server is properly configured to handle the workload.
431 |
432 | **Database Sharding:** If the database is too large to fit on a single server, consider sharding the database into smaller partitions that can be distributed across multiple servers. This can improve query performance by distributing the workload across multiple servers.
433 |
434 | * ## What is the issue with this query SELECT * FROM accounts WHERE id IN (SELECT account_id FROM account_data)?
435 |
436 | The issue with this query is that it uses a subquery in the WHERE clause, which can be inefficient and slow down query performance.
437 |
438 | Instead of using a subquery, you can rewrite the query using a JOIN operation to improve performance.
439 |
440 | also using `IN` operator can be slow when the subquery returns a large number of rows.
441 |
442 | ```sql
443 |
444 | SELECT a.*
445 | FROM accounts a
446 | JOIN account_data ad ON a.id = ad.account_id;
447 |
448 | ```
449 |
450 | * ### Imagine You have a table called projects that stores information about project timelines with the following columns:
451 | ```
452 | id
453 | name
454 | start_date
455 | end_date
456 | ```
457 | Write one SQL query that returns a summary in a single row with the following columns:
458 |
459 | * total: total number of projects
460 | * upcoming: projects that haven’t started yet (start_date > NOW())
461 | * in_progress: projects currently running (start_date <= NOW() AND end_date >= NOW())
462 | * finished: projects that have already ended (end_date < NOW())
463 |
464 | ```sql
465 | SELECT
466 | COUNT(*) AS total,
467 | COUNT(CASE WHEN start_date > NOW() THEN 1 END) AS upcoming,
468 | COUNT(CASE WHEN start_date <= NOW() AND end_date >= NOW() THEN 1 END) AS in_progress,
469 | COUNT(CASE WHEN end_date < NOW() THEN 1 END) AS finished
470 | FROM projects;
471 | ```
472 |
473 | * ### You have a table called payments with the following columns:
474 | ```
475 | id
476 | user_id
477 | payment_date
478 | amount
479 | ```
480 |
481 | Write a SQL query to fetch the latest 2 payments for each user, based on payment_date in descending order.
482 |
483 | Example Data
484 |
485 | | id | user_id | payment_date | amount |
486 | | -- | ------- | ------------ | ------ |
487 | | 1 | 201 | 2025-09-20 | 100 |
488 | | 2 | 201 | 2025-09-25 | 150 |
489 | | 3 | 201 | 2025-09-30 | 200 |
490 | | 4 | 202 | 2025-09-22 | 300 |
491 | | 5 | 202 | 2025-09-28 | 250 |
492 | | 6 | 202 | 2025-09-10 | 100 |
493 |
494 | ✅ Expected Output
495 |
496 | | id | user_id | payment_date | amount |
497 | | -- | ------- | ------------ | ------ |
498 | | 3 | 201 | 2025-09-30 | 200 |
499 | | 2 | 201 | 2025-09-25 | 150 |
500 | | 5 | 202 | 2025-09-28 | 250 |
501 | | 4 | 202 | 2025-09-22 | 300 |
502 |
503 | ```sql
504 | SELECT id, user_id, payment_date, amount
505 | FROM (
506 | SELECT
507 | id,
508 | user_id,
509 | payment_date,
510 | amount,
511 | ROW_NUMBER() OVER (
512 | PARTITION BY user_id
513 | ORDER BY payment_date DESC
514 | ) AS rn
515 | FROM payments
516 | ) AS ranked
517 | WHERE rn <= 2
518 | ORDER BY user_id, payment_date DESC;
519 |
520 | ```
--------------------------------------------------------------------------------
/src/fundamentals.md:
--------------------------------------------------------------------------------
1 | * ## What is Object-Oriented Programming?
2 | paradigm that relies on the concept of classes and objects.
3 | It is used to structure a software program into simple, reusable pieces of code.
4 | grouping similar tasks into classes
5 | to use it in many places and following (DRY) principle.
6 |
7 | * ## What is Encapsulation?
8 | Hiding information,
9 | or creating a black box around objects and asking yourself what properties and methods can be accessed outside of class
10 |
11 | * ## What is Inheritance?
12 | A mechanism in which one class acquires the property of another class.
13 | For example, a child inherits parents' properties and methods.
14 |
15 | * ## What is the difference between public, private, and protected?
16 | `public` members are accessible from outside the class.
17 |
18 | `private` members are only accessible from within the class.
19 |
20 | `protected` members are accessible from within the class and any subclasses.
21 |
22 | * ## What is the difference between abstract class and interface?
23 | An abstract class can have both abstract and non-abstract methods, while an interface can only have abstract methods.
24 |
25 | A class can inherit from only one abstract class, but it can implement multiple interfaces.
26 |
27 | All the methods in the interface must be in the public visibility scope.
28 |
29 | * ## Can the abstract class have a constructor?
30 | Yes, abstract class can have a constructor.
31 |
32 | * ## Can the abstract class have non-abstract methods?
33 | Yes, abstract class can have non-abstract methods.
34 |
35 | * ## Why do you use abstract classes?
36 | The purpose of this is
37 | to provide a template to inherit from and to force the inheriting class to implement the abstract methods.
38 |
39 | When inheriting from an abstract class,
40 | the child must define all methods marked abstract in the parent's class declaration
41 |
42 | * ## What is Polymorphism?
43 | Polymorphism is the ability of an object to take on many forms.
44 |
45 |
46 |
47 | Example
48 |
49 | ```php
50 | class Animal {
51 | public function makeSound() {
52 | return "Some sound";
53 | }
54 | }
55 |
56 | class Dog extends
57 | Animal {
58 | public function makeSound() {
59 | return "Bark";
60 | }
61 | }
62 |
63 | class Cat extends
64 | Animal {
65 | public function makeSound() {
66 | return "Meow";
67 | }
68 | }
69 |
70 | $animal = new Animal();
71 | $dog = new Dog();
72 | $cat = new Cat();
73 |
74 | echo $animal->makeSound(); // Output: Some sound
75 | echo $dog->makeSound(); // Output: Bark
76 | echo $cat->makeSound(); // Output: Meow
77 | ```
78 |
79 |
80 | * ## What are Solid Principles?
81 | SOLID is an acronym for five design principles intended to make software designs more understandable, flexible, and maintainable.
82 |
83 | - **Single Responsibility Principle (SRP):** A class should have one, and only one, reason to change.
84 | - **Open/Closed Principle (OCP):** You should be able to extend a class's behavior without modifying it.
85 | - **Liskov Substitution Principle (LSP):** Objects in a program should be replaceable with instances of their subtypes without altering the correctness of that program.
86 | Another explanation is: parent class can be replaced with child class without breaking the application.
87 | - **Interface Segregation Principle (ISP):** A client should never be forced to implement an interface that it doesn't use or clients shouldn't be forced to depend on methods they do not use.
88 | - **Dependency Inversion Principle (DIP):** High-level modules should not depend on low-level modules. Both should depend on abstractions. Abstractions should not depend on details. Details should depend on abstractions.
89 | Another explanation is: Depend on abstraction, not on concrete.
90 |
91 | * ## What is DRY?
92 | **Don't Repeat Yourself (DRY):** is a principle of software development aimed at reducing repetition of software patterns, to avoid redundancy.
93 |
94 | * ## What is YAGNI?
95 | **You Aren't Gonna Need It (YAGNI):** is a principle that states a programmer should not add functionality until deemed necessary.
96 |
97 | * ## What is KISS?
98 | **Keep It Simple, Stupid (KISS):** Most systems work best if they are kept simple rather than made complicated.
99 |
100 | * ## what is the difference between composition and inheritance?
101 | Composition and inheritance are two fundamental concepts in object-oriented programming
102 | that define relationships between classes.
103 | Here's a brief overview of each:
104 |
105 | **Inheritance:**
106 | - Inheritance is a mechanism where a new class (subclass or derived class) is created based on an existing class
107 | (superclass or base class).
108 | - The subclass inherits attributes and behaviors (methods) from the superclass.
109 | - It promotes code reusability and establishes an "is-a" relationship between classes.
110 | - Example: Dog and Cat classes can inherit from a Animal superclass because they are types of animals.
111 |
112 | **Composition:**
113 | - Composition is a concept where a class is composed of one or more objects of other classes.
114 | The composed objects are typically referred to as "components" or "parts."
115 | - Unlike inheritance,
116 | composition does not inherit behavior but rather includes behavior from other classes by creating instances of them.
117 | - It promotes code reusability and establishes a "has-a" relationship between classes.
118 | - Example: A Car class may have an Engine class and Wheel class as its components.
119 |
120 | In summary, inheritance is about "is-a" relationships and promotes code reuse by deriving one class from another,
121 | while composition is about "has-a" relationships
122 | In general,
123 |
124 | composition is often preferred over inheritance because it promotes looser coupling between classes
125 | and allows for more flexible and maintainable code.
126 | However, inheritance can still be useful in situations where there is a clear and natural hierarchy among classes
127 |
128 | * ## what is the difference between a docker and a virtual machine?
129 | Docker and virtual machines (VMs) are both used to deploy and run applications in isolated environments.
130 |
131 | Here are some key differences between Docker and virtual machines:
132 |
133 | **Architecture:**
134 | - VMs: VMs run on a hypervisor, which abstracts physical hardware and allows multiple VMs to run on a single physical machine. Each VM includes a complete operating system, virtualized hardware, and a full set of binaries required to run applications.
135 | - Docker: Docker uses containerization to package applications and their dependencies into isolated containers. Containers share the host machine's kernel and run as isolated processes, providing lightweight, portable, and efficient application deployment.
136 |
137 | **Resource Efficiency:**
138 | - VMs: VMs are heavier in terms of resource usage because they require a full operating system to be loaded for each instance, including memory, disk space, and CPU.
139 | - Docker: Docker containers are lightweight, as they share the host machine's kernel and only require resources for the application and its dependencies. This makes Docker more resource-efficient than VMs.
140 |
141 | **Isolation:**
142 | - VMs: VMs provide strong isolation, as each VM has its own virtualized hardware and runs its own operating system, making them suitable for running multiple different operating systems on the same physical machine.
143 | - Docker: Docker containers are less isolated than VMs because they share the host machine's kernel. However, they provide sufficient isolation for most applications and offer better performance and efficiency.
144 |
145 | **Portability:**
146 | - VMs: VMs are less portable because they require a hypervisor to run, which may not be available on all systems. Moving VMs between different hypervisors or cloud providers can be complex.
147 | - Docker: Docker containers are highly portable, as they include all dependencies and configurations required to run the application. Containers can be easily moved between different environments that support Docker.
148 |
149 | **Startup Time:**
150 | - VMs: VMs typically have longer startup times because they need to boot a full operating system.
151 | - Docker: Docker containers have faster startup times because they do not need to boot an entire operating system, only the application and its dependencies.
152 |
153 | * ## What is PWA?
154 | Progressive Web Apps
155 | converting your website into a mobile app that can be deployed as an app and can be used as an offline service
156 |
157 | * ## What is final keyword in OOB?
158 | The `final` keyword is used to restrict the inheritance of a class or the overriding of a method.
159 |
160 | When a class is declared as `final`, it cannot be subclassed or extended by other classes.
161 |
162 | When a method is declared as `final`, it cannot be overridden by subclasses.
163 |
164 | * ## What is dependency injection?
165 | Dependency injection is a design pattern in which a class receives its dependencies from external sources rather than creating them itself.
166 | This pattern promotes loose coupling between components, making the code more maintainable, testable, and reusable
167 |
168 | * ## What is Active record?
169 | An active record pattern is an approach to accessing data in a database.
170 | A database table is wrapped into a class.
171 | an object instance is tied to a single row in the table.
172 | After the creation of an object, a new row is added to the table upon the save method.
173 | Any object loaded gets its information from the database.
174 | When an object is updated, the corresponding row in the table is also updated.
175 | The wrapper class implements accessor methods
176 |
177 | more about Active record
178 |
179 | Active record
180 |
181 | * ## What is Data mapper?
182 | A Data Mapper is a Data Access Layer that performs bidirectional data transfer between a persistent data store (often a relational database) and an in-memory data representation (the domain layer).
183 | The goal of the pattern is to keep the in-memory representation and the persistent data store independent of each other and the data mapper itself
184 |
185 | * ## What is a Decorator design pattern?
186 | is a structural pattern
187 | that allows adding new behaviors to objects dynamically by placing them inside particular wrapper objects,
188 | called decorators.
189 |
190 |
191 |
192 | Example
193 |
194 | ```php
195 | interface Coffee {
196 | public function cost();
197 | }
198 |
199 | class SimpleCoffee implements Coffee {
200 | public function cost() {
201 | return 10;
202 | }
203 | }
204 |
205 | class MilkCoffee implements Coffee {
206 | protected $coffee;
207 |
208 | public function __construct(Coffee $coffee) {
209 | $this->coffee = $coffee;
210 | }
211 |
212 | public function cost() {
213 | return $this->coffee->cost() + 5;
214 | }
215 | }
216 |
217 | class WhipCoffee implements Coffee {
218 | protected $coffee;
219 |
220 | public function __construct(Coffee $coffee) {
221 | $this->coffee = $coffee;
222 | }
223 |
224 | public function cost() {
225 | return $this->coffee->cost() + 2;
226 | }
227 | }
228 |
229 | $coffee = new SimpleCoffee();
230 | echo $coffee->cost(); // Output: 10
231 |
232 | $coffee = new MilkCoffee($coffee);
233 | echo $coffee->cost(); // Output: 15
234 |
235 | $coffee = new WhipCoffee($coffee);
236 | echo $coffee->cost(); // Output: 17
237 | ```
238 |
239 |
240 |
241 |
242 | * ## Memcached VS Redis?
243 |
244 | Memcached and Redis are both popular in-memory caching systems, but they have some differences in terms of features, performance, and use cases.
245 |
246 | **Memcached:**
247 |
248 | - **Data Structures:** Memcached is a simple key-value store with no support for complex data structures.
249 | - **Data Persistence:** Memcached does not support data persistence by default, so data is lost when the server restarts.
250 | - **Replication:** Memcached does not support built-in replication.
251 | - **Use Cases:** Memcached is well-suited for simple caching needs where high-performance and simplicity are more important than advanced features.
252 |
253 | **Redis:**
254 |
255 | - **Data Structures:** Redis supports various data structures such as strings, lists, sets, sorted sets, and hashes, making it more versatile for different use cases.
256 | - **Data Persistence:** Redis supports various persistence options, including snapshots and append-only files (AOF), allowing data to be saved to disk.
257 | - **Replication:** Redis supports master-slave replication, allowing for data redundancy and high availability.
258 | - **Advanced Features:** Redis includes advanced features such as transactions, pub/sub messaging, and Lua scripting, making it suitable for a wide range of use cases beyond simple caching.
259 | - **Use Cases:** Redis is suitable for use cases that require more than simple key-value caching, such as real-time analytics, message queuing, and leaderboards.
260 |
261 | * ## How to scale a web application?
262 | Scaling a web application involves increasing its capacity to handle more traffic, users, and data without sacrificing performance or reliability.
263 |
264 | Here are some common strategies for scaling a web application:
265 |
266 | **Vertical Scaling:**
267 | - Vertical scaling involves increasing the capacity of a single server by adding more resources, such as CPU, memory, or storage.
268 | - This approach is relatively simple but has limitations in terms of scalability and cost-effectiveness.
269 |
270 | **Horizontal Scaling:**
271 |
272 | - Horizontal scaling involves adding more servers to distribute the load across multiple machines.
273 | - This approach is more scalable and cost-effective than vertical scaling but requires additional infrastructure and configuration.
274 | - Load Balancing: Load balancing distributes incoming traffic across multiple servers to ensure optimal performance and availability.
275 | - Caching: Caching frequently accessed data or content can reduce the load on the database and improve response times.
276 | - Database Sharding: Database sharding involves partitioning a database into smaller, more manageable pieces to distribute the load across multiple servers.
277 | - Content Delivery Networks (CDNs): CDNs cache static content on servers located closer to users, reducing latency and improving performance.
278 | - Microservices Architecture: Microservices break down an application into smaller, independent services that can be deployed, scaled, and maintained separately.
279 | - Auto-Scaling: Auto-scaling automatically adjusts the number of servers based on traffic patterns, ensuring optimal performance and cost efficiency.
280 |
281 | * ## What is the difference between a monolithic and microservices architecture?
282 | Monolithic and microservices architectures are two different approaches to designing and building software applications.
283 |
284 | **Monolithic Architecture:**
285 |
286 | - In a monolithic architecture, the entire application is built as a single, self-contained unit.
287 | - All components of the application, such as the user interface, business logic, and data access layer, are tightly coupled and run as a single process.
288 | - Monolithic applications are typically easier to develop, test, and deploy but can become complex and difficult to maintain as they grow in size and complexity.
289 | - Scaling a monolithic application involves scaling the entire application, which can be inefficient and costly.
290 |
291 | **Microservices Architecture:**
292 |
293 | - In a microservices architecture, the application is broken down into smaller, independent services that communicate with each other through APIs.
294 | - Each service is responsible for a specific function or feature of the application and can be developed, deployed, and scaled independently.
295 | - Microservices architectures promote modularity, flexibility, and scalability but can introduce complexity in terms of service communication, data consistency, and deployment orchestration.
296 | - Scaling a microservices application involves scaling individual services based on demand, allowing for more efficient resource utilization and cost management.
297 | - Microservices architectures are well-suited for large, complex applications with diverse requirements and technologies but require careful design and management to be successful.
298 |
299 |
300 | * ## what is use of API Gateway?
301 | An API Gateway is a server that acts as an API front-end,
302 | receiving API requests, enforcing throttling and security policies,
303 | passing requests to the back-end service, and then passing the response back to the requester.
304 |
305 | like a reverse proxy, accepting a request and routing it to the appropriate service.
306 |
307 | API Gateway can provide functionality such as authentication,
308 | rate limiting, caching, request and response transformations,
309 | and logging and monitoring and caching, and load balancing, and security,
310 | and API versioning, and error handling, and routing.
311 |
312 | technologies used in API Gateway include Amazon API Gateway, Apigee,
313 | NGINX, Azure API Management.
314 |
315 | * ## What is Swagger?
316 | Swagger is a set of open-source tools built around the OpenAPI Specification that can help you design, build, document,
317 | and consume RESTful web services.
318 |
319 | * ## What is the different between basic authentication and bearer token?
320 | Basic Authentication sends HTTP requests with the Authorization header
321 | that contains the word Basic followed by a space and a base64-encoded string username:password.
322 |
323 | --header 'Authorization: Basic d2ViYXBpOkR3QSFoZWZHUDIx'
324 |
325 | Bearer Token sends HTTP requests with the Authorization header
326 | that contains the word Bearer followed by a space and a token.
327 |
328 | the token can be decoded to get the user information.
329 |
330 | --header 'Authorization: Bearer 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'
331 |
332 | * ## What is the difference cookies and local storage?
333 | Cookies and local storage are two ways to store data in a web browser, but they have some key differences:
334 |
335 | **Cookies:**
336 |
337 | - Small pieces of data stored in the browser that are sent with every HTTP request to the server, which can impact performance and increase network traffic.
338 | - It Has a size limit of 4KB and can store up to 20 cookies per domain.
339 | - It Can be set with an expiration date and can be used for session management.
340 | - Vulnerable to cross-site scripting (XSS) attacks and can be accessed by both the server and client-side scripts.
341 | - Is accessible via the `document.cookie` object in JavaScript and can be used to store and retrieve data using key-value pairs.
342 |
343 | **Local Storage:**
344 |
345 | - Feature of modern web browsers that allows data to be stored locally on the user's device.
346 | - Has a size limit of 5MB per domain and is not sent with HTTP requests to the server.
347 | - Persistent and remains stored even after the browser is closed and reopened.
348 | - Used for storing user preferences, settings, and other data that does not need to be sent to the server.
349 | - Not vulnerable to XSS attacks and can only be accessed by client-side scripts running in the same domain.
350 | - More secure than cookies but may not be suitable for storing sensitive data.
351 | - Is accessible via the `localStorage` object in JavaScript and can be used to store and retrieve data using key-value pairs.
352 |
353 |
354 | * ## What is a Singleton and why it is not recommended?
355 | The Singleton design pattern is a creation pattern
356 | that ensures a class has only one instance and provides a global point of access to that instance.
357 |
358 | it is considered an anti-pattern due to the following reasons:
359 |
360 | **Global State:**
361 | - Singletons introduce global state into an application, making it harder to manage and test.
362 | - Global state can lead to tight coupling between components and make it difficult to reason about the flow of data and dependencies.
363 | - Difficult to Test: Singletons can make unit testing more challenging because they introduce hidden dependencies and shared state.
364 | - Singletons can make it difficult to isolate and test individual components in isolation.
365 | - Violates Single Responsibility Principle: Singletons can violate the Single Responsibility Principle by combining the responsibilities of creating an instance and managing its lifecycle.
366 |
367 | **Concurrency Issues:**
368 | - Singletons can introduce concurrency issues in multi-threaded environments.
369 |
370 | **Difficult to Extend:**
371 | - Singletons can be difficult to extend or modify because they rely on static methods and state.
372 | - Changing the behavior of a Singleton can require modifying the class itself, which can lead to code changes in multiple places.
373 | - Difficult to Mock: Singletons can be difficult to mock or replace with test doubles in unit tests.
374 |
375 | * ## What is key-clock and why it is used?
376 | Keycloak is an open-source identity and access management solution that provides features such as single sign-on,
377 | social login, and centralized user management.
378 |
379 | Keycloak can be used to secure applications and services by providing authentication,
380 | authorization, and user management capabilities.
381 |
382 | * ## What is identity server and why it is used?
383 | IdentityServer is an open-source identity and access management solution that provides features such as single sign-on,
384 | social login, and centralized user management.
385 |
386 | IdentityServer can be used to secure applications and services by providing authentication, authorization,
387 |
388 | * ## What is a Repository design pattern?
389 | The Repository design pattern is a design pattern
390 | that separates the data access logic from the business logic in an application.
391 |
392 | The Repository acts as an intermediary between the data source and the business logic,
393 | providing a clean and consistent interface for accessing data using dependency injection.
394 |
395 | The Repository pattern provides a way to centralize data access logic and abstract the underlying data store,
396 | making it easier to test and maintain the application.
397 |
398 | additional benefits
399 |
400 | **Flexibility**: You can easily change the data source (for example, switch from a database to an external API) without affecting the rest of the application.
401 |
402 | **Reusability**: Repositories allow you to reuse logic in multiple parts of your app, reducing code duplication.
403 |
404 | **Testability**: It’s easier to test, as you can mock or replace the repository during testing.
405 |
406 | **Organization & Clarity**: Repositories keep your code clean and structured, making it easier to understand and maintain.
407 |
408 |
409 |
410 |
411 | Example
412 |
413 | ```php
414 | interface UserRepositoryInterface {
415 | public function findById($id);
416 | public function findByEmail($email);
417 | public function save(User $user);
418 | public function delete(User $user);
419 | }
420 |
421 | class UserRepository implements UserRepositoryInterface {
422 | public function findById($id) {
423 | // Implementation
424 | }
425 |
426 | public function findByEmail($email) {
427 | // Implementation
428 | }
429 |
430 | public function save(User $user) {
431 | // Implementation
432 | }
433 |
434 | public function delete(User $user) {
435 | // Implementation
436 | }
437 | }
438 |
439 | class UserService
440 | {
441 | protected $userRepository;
442 |
443 | public function __construct(UserRepositoryInterface $userRepository)
444 | {
445 | $this->userRepository = $userRepository;
446 | }
447 |
448 | public function getUserById($id)
449 | {
450 | return $this->userRepository->findById($id);
451 | }
452 |
453 | public function saveUser(User $user)
454 | {
455 | return $this->userRepository->save($user);
456 | }
457 | }
458 | ```
459 |
460 |
461 |
462 |
463 |
464 | * ## What is a Factory method design pattern?
465 | The Factory Method design pattern is a creational pattern
466 | that provides an interface for creating objects in a superclass
467 |
468 | but it allows subclasses to alter the type of objects that will be created.
469 |
470 | It promotes loose coupling between the creator and the product,
471 |
472 | allowing the creator to delegate the responsibility of creating objects to subclasses.
473 |
474 |
475 |
476 | Example
477 |
478 | ```php
479 | interface Vehicle {
480 | public function drive();
481 | }
482 |
483 | class Car implements Vehicle {
484 | public function drive() {
485 | return 'Driving a car';
486 | }
487 | }
488 |
489 | class Truck implements Vehicle {
490 | public function drive() {
491 | return 'Driving a truck';
492 | }
493 | }
494 |
495 | interface VehicleFactory {
496 | public function createVehicle();
497 | }
498 |
499 | class CarFactory implements VehicleFactory {
500 | public function createVehicle() {
501 | return new Car();
502 | }
503 | }
504 |
505 | class TruckFactory implements VehicleFactory {
506 | public function createVehicle() {
507 | return new Truck();
508 | }
509 | }
510 |
511 | $carFactory = new CarFactory();
512 |
513 | $car = $carFactory->createVehicle();
514 | echo $car->drive(); // Output: Driving a car
515 |
516 | $truckFactory = new TruckFactory();
517 |
518 | $truck = $truckFactory->createVehicle();
519 |
520 | echo $truck->drive(); // Output: Driving a truck
521 | ```
522 |
523 |
524 |
525 | * ## What is the difference between Hashing and Encryption?
526 |
527 | **Hashing:**
528 |
529 | - Hashing is a one-way process that converts input data into a fixed-size string of bytes.
530 | - Hash functions are deterministic, meaning the same input will always produce the same output.
531 | - Hashing is used to verify data integrity, generate checksums, and store passwords securely.
532 | - like md5, sha1, sha256, sha512
533 |
534 | **Encryption:**
535 |
536 | - Encryption is a two-way process that converts input data into a ciphertext that can be decrypted back into the original data.
537 | - Encryption uses keys to encrypt and decrypt data, providing confidentiality and privacy.
538 | - Encryption is used to protect sensitive data, secure communications, and prevent unauthorized access.
539 | - like AES, DES, RSA
540 |
541 | * ## What is a Strategy design pattern?
542 |
543 | The Strategy design pattern is a behavioral pattern
544 |
545 | that defines a family of algorithms, encapsulates each algorithm, and makes them interchangeable.
546 |
547 | * ## How dependency container works?
548 |
549 | A dependency container is a design pattern that allows objects to be created and managed by an external container.
550 |
551 | The container is responsible for instantiating objects, managing their dependencies, and providing them to other objects that need them.
552 |
553 | The container uses a configuration file or code to define the relationships between objects and their dependencies.
554 |
555 | When an object requests a dependency from the container,
556 | the container resolves the dependency and provides it to the object.
557 |
558 | Dependency containers promote loose coupling between components,
559 | improve code reusability, and make it easier to test and maintain applications.
560 |
561 | * ## How many type of debenency injection we have?
562 |
563 | There are three types of dependency injection:
564 |
565 | **Constructor Injection:**
566 |
567 | - Dependencies are provided to a class through its constructor.
568 | - Constructor injection ensures that all dependencies are provided when an object is created.
569 | - Constructor injection promotes immutability and makes dependencies explicit.
570 |
571 | **Setter Injection:**
572 |
573 | - Dependencies are provided to a class through setter methods.
574 | - Setter injection allows dependencies to be set or changed after an object is created.
575 | - Setter injection is more flexible than constructor injection but can lead to mutable objects.
576 |
577 | **Method Injection:**
578 |
579 | - Dependencies are provided to a class through method parameters.
580 | - Method injection allows dependencies to be passed to specific methods as needed.
581 | - Method injection is useful for providing dependencies to specific methods without affecting the class's state.
582 |
583 | * ## How do we decide that a particular domain problem should be converted into microservices?
584 |
585 | Deciding whether to convert a particular domain problem into microservices involves considering several factors:
586 |
587 | **Scalability:**
588 |
589 | - Scaled independently, allowing specific services to be scaled based on demand.
590 |
591 | **Complexity:**
592 |
593 | - Manage complexity by breaking down a large application into smaller, more manageable services.
594 |
595 | **Isolation:**
596 |
597 | - Isolation between services, allowing failures in one service to be contained and not affect other services.
598 |
599 | **Technology Stack:**
600 |
601 | - Allow different services to be developed using different technologies and frameworks.
602 |
603 | **Deployment Flexibility:**
604 |
605 | - Deployed independently, allowing services to be updated and deployed without affecting other services.
606 |
607 | **Performance:**
608 |
609 | - Improve performance by allowing services to be optimized and scaled independently.
610 |
611 | **Data Management:**
612 |
613 | - Manage data by allowing each service to have its own data store or database.
614 |
615 | **Cost:**
616 |
617 | - Increase infrastructure and operational costs due to the need for additional services and infrastructure.
618 |
619 | * ## Facade Design Pattern:
620 |
621 | The Facade design pattern is a structural pattern that provides a simplified interface to a complex subsystem.
622 |
623 | pros:
624 | * Simplifies usage of complex systems.
625 | * Reduces dependencies between client code and subsystems.
626 | * Encapsulates changes — if subsystems change, client code stays the same.
627 |
628 | cons:
629 | * Hides functionality — advanced users may lose flexibility.
630 | * It Can become a god class if it grows too large.
631 | * Adds an extra layer, which may slightly affect performance in large systems.
632 |
633 |
634 | * ## What is service oriented architecture (SOA)?
635 | Service-Oriented Architecture (SOA) is a design pattern
636 | that structures an application as a collection of loosely coupled services.
637 | Each service represents a specific business function and communicates with other services through well-defined interfaces and protocols.
638 | SOA promotes reusability, scalability, and flexibility by allowing services to be developed, deployed, and maintained independently.
639 |
640 | example of SOA:
641 | using services classes in project like authentication service, payment service, notification service, etc.
642 |
643 |
644 |
645 |
646 |
647 |
--------------------------------------------------------------------------------