Unit1 - Subjective Questions
INT221 • Practice Questions with Detailed Answers
Explain the MVC architecture and describe the role of each of its three components.
Model-View-Controller (MVC) is an architectural pattern that separates an application into three main logical components: the Model, the View, and the Controller. This separation helps to manage complexity when building applications.
Components:
- Model:
- The Model represents the data and the business logic of the application.
- It retrieves data from the database and persists data back to it.
- In Laravel, this is handled via Eloquent ORM.
- View:
- The View is the User Interface (UI). It displays data to the user.
- It contains HTML, CSS, and client-side JavaScript.
- In Laravel, Views are typically created using the Blade templating engine.
- Controller:
- The Controller acts as an interface between the Model and the View.
- It processes the incoming HTTP requests, interacts with the Model to fetch data, and passes that data to the View for rendering.
What is the Laravel Framework? Briefly list five of its key features.
Laravel is a free, open-source PHP web framework created by Taylor Otwell and intended for the development of web applications following the model–view–controller (MVC) architectural pattern. It is designed to make common web development tasks easier and faster.
Key Features:
- Eloquent ORM: An object-relational mapper that makes interacting with databases intuitive.
- Blade Templating Engine: A powerful template engine that does not restrict developers from using plain PHP code.
- Artisan Console: A built-in command-line interface for automating repetitive tasks.
- Migration System: Version control for database schemas, allowing teams to modify and share the application's database schema.
- Built-in Authentication: Laravel provides out-of-the-box support for authentication and authorization.
Describe the Request Lifecycle in a Laravel application with respect to the MVC pattern.
The Request Lifecycle describes how a request is handled from the moment it enters the application until the response is returned.
Steps in the Lifecycle:
- Entry Point (
index.php): All requests land on thepublic/index.phpfile, which loads the Composer autoloader and the Laravel application instance. - HTTP Kernel: The request is sent to the HTTP Kernel (
app/Http/Kernel.php). This handles middleware (e.g., session handling, CSRF protection). - Routing: The Service Container sends the request to the router. The router determines which Controller or closure should handle the request.
- Controller Action: The Controller executes logic. It may communicate with the Model to fetch or save data.
- View Rendering: The Controller passes data to the View. The View generates the final HTML.
- Response: The response is returned through the Kernel and sent back to the user's browser.
What is Composer? Explain its significance in modern PHP development.
Composer is a dependency manager for PHP. It allows developers to declare the libraries their project depends on and manages the installation and updating of these libraries.
Significance:
- Dependency Management: It automatically downloads libraries and their specific dependencies (recursive dependencies).
- Autoloading: It generates an
autoload.phpfile, allowing developers to use classes without manuallyincludeorrequirestatements. - Version Control: By using
composer.jsonandcomposer.lock, it ensures that every developer on a team installs exactly the same version of the packages. - Project Creation: It is the standard way to install frameworks like Laravel (e.g.,
composer create-project).
Differentiate between composer.json and composer.lock files.
| Feature | composer.json |
composer.lock |
|---|---|---|
| Definition | A configuration file defining project details and required dependencies (with version constraints). | A file generated after installation that records the exact versions of packages installed. |
| Role | Tells Composer which packages should be installed. | Tells Composer which packages were installed to ensure consistency. |
| Editability | Manually edited by the developer or updated via commands. | Should not be manually edited; generated automatically. |
| Usage in Teams | Used to define requirements. | Used to ensure all team members have the identical environment. |
Write the command to install the latest version of Laravel via Composer and explain the command parameters.
To install the latest version of Laravel via Composer, the following command is used:
bash
composer create-project laravel/laravel example-app
Explanation of Parameters:
composer: Invokes the Composer executable.create-project: The command to clone a package and install its dependencies to create a new project.laravel/laravel: The package name (Vendor/Package) to install.example-app: The name of the directory where the application will be created (this is your project name).
Note: To force a specific version, one might add the version number, e.g., "laravel/laravel:^10.0".
What are the server requirements for installing the latest Laravel framework? (Mention at least 4 PHP extensions).
To run the latest Laravel framework, the server must meet specific requirements, primarily regarding the PHP version and installed extensions.
Requirements:
- PHP Version: Must be PHP 8.1 or higher (depending on the specific Laravel version).
- BCMath PHP Extension
- Ctype PHP Extension
- Fileinfo PHP Extension
- JSON PHP Extension
- Mbstring PHP Extension
- OpenSSL PHP Extension
- PDO PHP Extension
- Tokenizer PHP Extension
- XML PHP Extension
Provide a detailed overview of the Laravel Directory Structure. Explain the purpose of any five root directories.
Laravel follows a specific directory structure to organize code.
Key Directories:
app/: Contains the core code of the application (Models, Controllers, Middleware). Most of the development happens here.config/: Contains all of the application's configuration files (database settings, mail settings, app execution settings).database/: Contains database migrations, model factories, and seeds.public/: The web server's document root. It contains theindex.phpfile (entry point) and assets like images, JavaScript, and CSS.resources/: Contains uncompiled assets such as raw CSS/SCSS, JavaScript, and the Blade templates (views).routes/: Contains all of the route definitions for the application (e.g.,web.php,api.php).vendor/: Contains the Composer dependencies.
Explain the purpose of the routes directory in Laravel and list the default route files found within it.
The routes directory defines how the application responds to client requests via URLs.
Default Route Files:
web.php: Contains routes that theRouteServiceProviderplaces in thewebmiddleware group. These routes provide features like session state, CSRF protection, and cookie encryption. Used for standard web interface interactions.api.php: Contains routes placed in theapimiddleware group. These are stateless and usually require token authentication. Used for API development.console.php: Defines closure-based console commands (Artisan commands).channels.php: Registers all of the event broadcasting channels for real-time applications.
What is the difference between the public directory and the resources directory in Laravel?
public Directory:
- This is the entry point for the web server.
- It contains the
index.phpfile. - It stores compiled or static assets accessible directly by the browser, such as images, compiled CSS, and compiled JavaScript bundles.
resources Directory:
- This directory contains the source code for assets.
- It holds raw, uncompiled files like SASS/SCSS, raw JavaScript, and language files.
- It also contains the Views (Blade templates) which are rendered by the server before being sent to the browser.
What is Artisan in Laravel? How is it accessed?
Artisan is the command-line interface (CLI) included with Laravel. It provides a number of helpful commands for use while building an application.
Accessing Artisan:
It is accessed via the terminal in the root of the Laravel project using the PHP executable:
bash
php artisan list
It is driven by the powerful Symfony Console component.
List five common Artisan commands and explain their usage.
php artisan serve: Starts the local development server (typically at http://localhost:8000).php artisan make:controller [Name]: Creates a new Controller class file inapp/Http/Controllers.php artisan make:model [Name]: Creates a new Eloquent Model class.php artisan migrate: Runs the database migrations to update the database schema.php artisan route:list: Displays a list of all registered routes in the application, including their methods, URIs, and middleware.
How does Blade Templating facilitate MVC development in Laravel?
Blade is Laravel's powerful templating engine used for the View component of MVC.
- Inheritance: Blade allows defining a master layout (using
@extendsand@yield), reducing code duplication across different pages. - Data Display: It easily displays data passed from the Controller using double curly braces (e.g.,
{{ $name }}), which automatically escapes data to prevent XSS attacks. - Control Structures: It provides shortcuts for common PHP control structures like
@if,@foreach, and@auth. - Performance: Unlike some template engines, Blade views are compiled into plain PHP code and cached until they are modified, ensuring zero overhead.
Explain the role of the .env file in a Laravel application.
The .env file serves as the configuration file for environment-specific variables.
- Environment Configuration: It allows developers to define different settings for local, staging, and production environments (e.g.,
APP_ENV=local). - Security: Sensitive credentials like database passwords (
DB_PASSWORD), API keys, and mail server credentials are stored here. - Git Exclusion: The
.envfile is included in.gitignoreby default, ensuring sensitive data is not committed to version control systems. - Access: Values are accessed in the code using the
env('KEY')helper function.
What is Eloquent ORM? How does it map databases to objects?
Eloquent ORM (Object-Relational Mapping) is Laravel's built-in database abstraction layer.
Mapping Concept:
- Active Record Implementation: Eloquent is an Active Record implementation, meaning each database table has a corresponding "Model" class.
- Table to Class: A table named
usersmaps to a model class namedUser. - Row to Object: Each instance of the
Usermodel represents a single row in theuserstable. - Interactions: Developers can query the database using PHP syntax (e.g.,
User::all()) rather than writing raw SQL, making the code more readable and maintainable.
Describe the steps to install Composer globally on a Windows machine.
To install Composer globally on Windows:
- Download: Visit
getcomposer.organd download theComposer-Setup.exeinstaller. - Run Installer: Run the executable file.
- PHP Path: During installation, Composer will ask for the location of
php.exe. Browse and select the PHP executable (e.g., inside XAMPP/WAMP folder). - Path Variable: The installer automatically adds Composer to the system
PATHenvironment variable. - Verification: Open a new Command Prompt terminal and type
composer. If the Composer logo and version details appear, the installation is successful.
What is the purpose of the php artisan tinker command?
php artisan tinker launches an interactive shell (REPL - Read-Eval-Print Loop) for the Laravel application.
Purpose:
- Testing Logic: It allows developers to interact with the entire Laravel application (Models, Classes, Events) from the command line without creating routes or controllers.
- Database Interaction: Developers can run Eloquent queries (e.g.,
User::find(1)) to inspect data quickly. - Debugging: It is useful for debugging code snippets and testing relationships between models in real-time.
Explain the concept of Namespace in the context of Laravel's application structure.
In Laravel, Namespaces are used to organize classes and prevent naming collisions, adhering to the PSR-4 autoloading standard.
- Structure Reflection: The namespace usually reflects the directory structure. For example, a controller located in
app/Http/Controllersusually has the namespaceApp\Http\Controllers. - The
AppNamespace: By default, the application logic under theapp/directory lives under theAppnamespace. - Autoloading: Composer uses these namespaces to automatically load files when a class is called, eliminating the need for
includestatements. - Grouping: It groups related classes (e.g., all Models, all Controllers), making large applications manageable.
Compare MVC with Flat PHP (Spaghetti Code) approaches.
| Feature | Flat PHP (Spaghetti Code) | MVC (Laravel) |
|---|---|---|
| Organization | Logic, Database queries, and HTML are mixed in single files. | Logic (Controller), Data (Model), and UI (View) are separated. |
| Maintainability | Hard to maintain; changing one part may break others. | Easy to maintain due to separation of concerns. |
| Reusability | Code reuse is difficult. | Models and Views can be reused easily. |
| Testing | Difficult to unit test. | Components can be tested independently. |
| Security | Developer must manually handle security (SQL injection, CSRF). | Framework provides built-in security features. |
How does Laravel handle application Maintenance Mode using Artisan?
Laravel provides an easy way to disable the application while updates are performed using Artisan commands.
- Enable Maintenance Mode:
Runphp artisan down. This will show a custom "Service Unavailable" view to all users. - Bypass:
You can specify a secret token to bypass maintenance mode:php artisan down --secret="1630542a-246b-4b66-afa1-dd72a4c43515". You can then access the site viayour-domain.com/1630542a...to set a cookie allowing access. - Disable Maintenance Mode:
Runphp artisan upto bring the application back online for all users.