Q1: What is Laravel?

Laravel is a free open source PHP Web framework created by Taylor Otwell to develop Web applications that follow the Model-View-Controller (MVC) architectural pattern.

Q2: What are the benefits of Laravel compared to other Php frameworks?

  • The setup and customization process is simple and fast compared to other frameworks.
  • Built-in authentication system
  • Support for multiple file systems
  • Pre-installed packages such as Laravel Socialite, Laravel Cashier, Laravel Elixir, Passport, Laravel Scout
  • Eloquent ORM for PHP Active Record Implementation
  • Built-in command line tool “Artisan” for creating code frameworks, database structures and building their migrations

Q3: Explain migration in Laravel

Laravel Migrations is similar to database versioning, allowing teams to easily modify and share the database schema of their applications. Migrations are often used in conjunction with Laravel’s Architecture generator to easily build an application’s database architecture.

Q4: What is the use of Facade Pattern?

Facades provide a static interface to classes available in an application’s service container. Laravel Facades, acting as a static proxy for the base classes in the service container, offers the advantage of a concise, expressive syntax while maintaining greater testability and flexibility than traditional static approaches.

All Laravel Facades are defined in the Illuminate\Support\ facades namespace.

To view:

use Illuminate\Support\Facades\Cache;

Route::get('/cache', function () {
    return Cache::get('key');
});
Copy the code

Q5: What is a service container?

The Laravel service container is a tool for managing class dependencies and performing dependency injection.

Q6: What is Eloquent Models?

Eloquent ORM, which comes with Laravel, provides a beautiful, simple implementation of ActiveRecord for working with databases. Each database table has a corresponding model for interacting with the table. The model lets you query data in a table and insert new records into the table.

Q7: What is the Laravel incident?

Laravel events provide a simple observer mode implementation that allows subscriptions and listening to events in the application. An event is an incident or event that a program detects and handles.

Here are some examples of events in Laravel:

  • New User registration
  • Post new comments
  • User login/logout
  • New products have been added.

Q8: What do you know about query generators in Laravel?

Laravel’s database query builder provides a convenient, smooth interface for creating and running database queries. It can be used to perform most database operations in an application and works on all supported database systems.

The Laravel query builder uses PDO parameter binding to protect applications from SQL injection attacks. There is no need to clean up strings passed as bindings.

Some features of the query generator:

  • block
  • The aggregation
  • Selects
  • A native method
  • Joins
  • Unions
  • Where clause
  • Grouping, Limit, & Offset

Q9: How are migrations generated?

Migration is like versioning of your database, enabling your team to easily modify and share the database schema of your application. Migration is often used in conjunction with Laravel’s Architecture builder to easily build the application’s database architecture.

To create a migration, use the make: migration Artisan command:

php artisan make:migration create_users_table
Copy the code

The new migrations will be placed in your Database/Migrations directory. Each migration file name contains a timestamp that allows Laravel to determine the migration order.

Q10: How do I mock a static facade method?

Facades provide “static” interfaces to classes available in the application’s service container. Unlike traditional static method calls, Facades can be mocked. We can mock a call to a static shanzhai method using the shouldReceive method, which returns an instance of Shanzhai Mock.

$value = Cache::get('key'); / / test Cache: : shouldReceive (' get ') - > once () - > with (' key ') - > andReturn (" value ");Copy the code

Q11: What are the benefits of Eager Loading and when to use it?

The relationship data is Lazy Loaded when the Eloquent relationship is accessed as a property. This means that the relational data is not actually loaded until you first access the property. However, Eloquent can be an Eager Load relationship when querying the parent model.

When we have nested objects (such as books -> authors), Eager Loading mitigated the problem of N + 1 queries. We can use Eager Loading to reduce this to just two queries.

Q12: What is the use of local scope?

Scopes allow you to easily reuse query logic in your model. To define scope, simply prefix the model method

Scope: class User extends Model {public function scopePopular($query) {return $query->where('votes', '>', 100); } public function scopeWomen($query) { return $query->whereGender('W'); }}Copy the code

Usage:

$users = User::popular()->women()->orderBy('created_at')->get();
Copy the code

Sometimes you might want to define a scope that takes parameters. Dynamic scopes accept query parameters:

class User extends Model { public function scopeOfType($query, $type) { return $query->whereType($type); }}Copy the code

Usage:

$users = User::ofType('member')->get();

Q13: What is the route name in Laravel?

Route naming makes it easier to reference routes when generating redirects or urls. You can specify a named route by adding the name method to the route definition:

Route::get('user/profile', function () {
    //
})->name('profile');
Copy the code

You can specify route names for controller operations:

Route::get('user/profile', 'UserController@showProfile')->name('profile');
Copy the code

After assigning a name to a route, you can use the route name with global routing functionality when generating urls or redirects:

// Generating URLs...
$url = route('profile');

// Generating Redirects...
return redirect()->route('profile');
Copy the code

Q14: What are closures in Laravel?

A closure is an anonymous function. Closures are typically used as callback methods and can be used as arguments in functions

function handle(Closure $closure) { $closure('Hello World! '); } handle(function($value){ echo $value; });Copy the code

Q15: List some of the aggregation methods provided by the query builder in Laravel?

An aggregation function is the ability to group multiple rows of values together as input under certain conditions to form a single value with more important meanings or measures (such as a set, package, or list).

Here is a list of some of the aggregation methods provided by the Laravel query builder:

The count () $products = DB: : table (" products ") - > count (); Max () $price = DB: : table (" orders ") - > Max (" price "); The min () $price = DB: : table (" orders ") - > min (" price "); Avg () * $price = DB: : table (" orders ") - > avg (" price "); The sum () $price = DB: : table (" orders ") - > sum (" price ");Copy the code

Q16: What is reverse routing in Laravel?

In Laravel, reverse routing generates urls based on route declarations. Reverse routing makes your application more flexible. For example, the following routing declaration tells Laravel to perform the “login” operation in the Users controller when the request URI is “login”.

Mysite.com/login Route: : get (" login ", "users @ login ');Copy the code

With reverse routing, we can create a link to it and pass any parameters we define. If no optional parameter is provided, it is removed from the generated link.

{{ HTML::link_to_action('users@login') }}
Copy the code

It creates a link in the view like mysite.com/login.

Q17: : Let’s create an enumeration for PHP to provide some code examples.

What if our code needs more validation of enumerated constants and values?

Depending on usage, I usually use something simple like the following:

abstract class DaysOfWeek
{
    const Sunday = 0;
    const Monday = 1;
    // etc.
}

$today = DaysOfWeek::Sunday;
Copy the code

This is an extended example that better serves a wider range of cases:

abstract class BasicEnum {
    private static $constCacheArray = NULL;

    private static function getConstants() {
        if (self::$constCacheArray == NULL) {
            self::$constCacheArray = [];
        }
        $calledClass = get_called_class();
        if (!array_key_exists($calledClass, self::$constCacheArray)) {
            $reflect = new ReflectionClass($calledClass);
            self::$constCacheArray[$calledClass] = $reflect - > getConstants();
        }
        return self::$constCacheArray[$calledClass];
    }

    public static function isValidName($name, $strict = false) {
        $constants = self::getConstants();

        if ($strict) {
            return array_key_exists($name, $constants);
        }

        $keys = array_map('strtolower', array_keys($constants));
        return in_array(strtolower($name), $keys);
    }

    public static function isValidValue($value, $strict = true) {
        $values = array_values(self::getConstants());
        return in_array($value, $values, $strict);
    }
}
Copy the code

We can use it as:

abstract class DaysOfWeek extends BasicEnum {
    const Sunday = 0;
    const Monday = 1;
    const Tuesday = 2;
    const Wednesday = 3;
    const Thursday = 4;
    const Friday = 5;
    const Saturday = 6;
}

DaysOfWeek::isValidName('Humpday');                  // false
DaysOfWeek::isValidName('Monday');                   // true
DaysOfWeek::isValidName('monday');                   // true
DaysOfWeek::isValidName('monday', $strict = true);   // false
DaysOfWeek::isValidName(0);                          // false

DaysOfWeek::isValidValue(0);                         // true
DaysOfWeek::isValidValue(5);                         // true
DaysOfWeek::isValidValue(7);                         // false
DaysOfWeek::isValidValue('Friday');                  // false
Copy the code

Q18: What are PHP auto-loaded classes?

Using the autoloader, PHP allows a class or interface to be loaded one last time before it fails due to an error.

The spl_autoload_register() function in PHP can register any number of autoloaders, even if classes and interfaces are undefined.

spl_autoload_register(function ($classname) {
    include  $classname . '.php';
});
$object  = new Class1();
$object2 = new Class2();
Copy the code

In the example above, we don’t need to include class.php and class.php. The spl_autoload_register() function will load class.php and class.php automatically.

Q19: Does PHP support method overloading?

Method overloading is the phenomenon of using the same method name with different signatures. Function signatures in PHP are based only on their names and do not contain argument lists, so you cannot have two functions with the same name, so PHP does not support method overloading.

However, you can declare a mutable function that takes a variable number of arguments. You can use func_num_args() and func_get_arg() to pass parameters and use them normally.

function myFunc() { for ($i = 0; $i < func_num_args(); $i++) { printf("Argument %d: %s\n", $i, func_get_arg($i)); }} /* Argument 0: a Argument 2: 3.5 */ myFunc('a', 2, 3.5);Copy the code

Q20: Why are Traits needed in Laravel?

Traits have been added to PHP for a simple reason: PHP does not support multiple inheritance. In short, a class cannot extend more than one class at a time. This becomes taxing when you need functionality declared in two different classes that are also used by other classes, and the result is that you have to execute code repeatedly to get the job done without entangling yourself.

Traits were introduced, which allows us to declare a class that contains multiple reusable methods. Better yet, their methods can be injected directly into any class you use, and you can use multiple traits in the same class. Let’s look at a simple Hello World example.

trait SayHello
{
    private function hello()
    {
        return "Hello ";
    }

    private function world()
    {
        return "World";
    }
}

trait Talk
{
    private function speak()
    {
        echo $this->hello() . $this->world();
    }
}

class HelloWorld
{
    use SayHello;
    use Talk;

    public function __construct()
    {
        $this->speak();
    }
}

$message = new HelloWorld(); // returns "Hello World";
Copy the code

Q21: What is Autoloader in PHP?

The autoloader defines methods to automatically include PHP classes in your code without using statements such as require and include.

The PSR-4 will support a simpler folder structure, but will make it impossible to know the exact path of a class just by looking at the fully qualified name.

The PSR-0 is a bit confusing on hard drives, but supports the old developer (the underlined user of the class name), and helps us identify the location of the class by looking at its name.

Q22: What does yield mean in PHP?

Explain this code and what yield does:

function a($items) { foreach ($items as $item) { yield $item + 1; }}Copy the code

The yield keyword returns data from the generator function. Generator functions are actually a more compact and efficient way to write iterators. It allows you to define a function that evaluates and returns values as you traverse the function.

Therefore, the function in question is almost identical to the following:

function b($items) {
    $result = [];
    foreach ($items as $item) {
        $result[] = $item + 1;
    }
    return $result;
}
Copy the code

There is only one difference, a() returns a generator, while B () is just a simple array. And both can be iterated over.

The generator version of the function does not allocate a full array and therefore requires less memory. Generators can be used to address memory limitations. Because generators only calculate their expressde value on demand, they are useful as a substitute for calculating sequences that are expensive or cannot be computed at once.

Q23:

What does $mean in PHP?

similar

The syntax for variable is called mutable variable.

Let’s try

$:

$real_variable = 'test';
$name = 'real_variable'; // variable variable for real variable
$name_of_name = 'name'; // variable variable for variable variable

echo $name_of_name . '<br />';
echo $$name_of_name . '<br />';
echo $$$name_of_name . '<br />';
Copy the code

Here is the output:

name
real_variable
test
Copy the code