main Flashcards

1
Q

Laravel Cashier

A

Laravel’s package for fully integrating Stripe or other payment methods with minimum effort

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

Multiple inheritance in PHP

A

There is no multiple inheritance in PHP, but there are better methods. Favor composition over inheritance, use traits, interfaces…

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

Final method

A

A child extending the parent can’t override the method declared as final

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

Final class

A

A final class is not able to be inherited / extended

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q

When to use final

A

Make your classes always final, if they implement an interface, and no other public methods are defined

  1. Preventing massive inheritance chain of doom
  2. Encouraging composition
  3. Force the developer to think about user public API
  4. Force the developer to shrink an object’s public API
  5. A final class can always be made extensible
  6. extends breaks encapsulation
  7. You don’t need that flexibility
  8. You are free to change the code
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
6
Q

When to avoid Final

A

When to avoid final:

Final classes only work effectively under following assumptions:

  1. There is an abstraction (interface) that the final class implements
  2. All of the public API of the final class is part of that interface

If one of these two pre-conditions is missing, then you will likely reach a point in time when you will make the class extensible, as your code is not truly relying on abstractions.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
7
Q

Laravel Passport vs Laravel Sanctum

A

If your application absolutely needs to support OAuth2, then you should use Laravel Passport.

However, if you are attempting to authenticate a single-page application, mobile application, or issue API tokens, you should use Laravel Sanctum. Laravel Sanctum does not support OAuth2; however, it provides a much simpler API authentication development experience.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
8
Q

Laravel Sanctum problems it solves

A

API Tokens

First, Sanctum is a simple package you may use to issue API tokens to your users without the complication of OAuth. This feature is inspired by GitHub and other applications which issue “personal access tokens”. For example, imagine the “account settings” of your application has a screen where a user may generate an API token for their account. You may use Sanctum to generate and manage those tokens. These tokens typically have a very long expiration time (years), but may be manually revoked by the user at anytime.

Laravel Sanctum offers this feature by storing user API tokens in a single database table and authenticating incoming HTTP requests via the Authorization header which should contain a valid API token.

SPA Authentication

Second, Sanctum exists to offer a simple way to authenticate single page applications (SPAs) that need to communicate with a Laravel powered API. These SPAs might exist in the same repository as your Laravel application or might be an entirely separate repository, such as a SPA created using Vue CLI or a Next.js application.

For this feature, Sanctum does not use tokens of any kind. Instead, Sanctum uses Laravel’s built-in cookie based session authentication services. Typically, Sanctum utilizes Laravel’s web authentication guard to accomplish this. This provides the benefits of CSRF protection, session authentication, as well as protects against leakage of the authentication credentials via XSS.

Sanctum will only attempt to authenticate using cookies when the incoming request originates from your own SPA frontend. When Sanctum examines an incoming HTTP request, it will first check for an authentication cookie and, if none is present, Sanctum will then examine the Authorization header for a valid API token.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
9
Q

Service Providers

A

Service providers are the central place of all Laravel application bootstrapping. Your own application, as well as all of Laravel’s core services, are bootstrapped via service providers.

But, what do we mean by “bootstrapped”? In general, we mean registering things, including registering service container bindings, event listeners, middleware, and even routes. Service providers are the central place to configure your application.

If you open the config/app.php file included with Laravel, you will see a providers array. These are all of the service provider classes that will be loaded for your application. By default, a set of Laravel core service providers are listed in this array. These providers bootstrap the core Laravel components, such as the mailer, queue, cache, and others. Many of these providers are “deferred” providers, meaning they will not be loaded on every request, but only when the services they provide are actually needed.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
10
Q

Traits

A

It’s a piece of code that doesn’t need to be instantiated. It’s used in a model for instance, and it gives you the posibility to reuse code without repeating. This is code that is “pasted” into your model, it’s not being extended, this means that if you have a method “hello()” in your model and a method “hello()” in your trait, you’ll experience an error. You can bypass this error this way:

use TestTrait {
hello as traitHello
}

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
11
Q

Que es Psalm y que significa (errorLevel=”3”)

A

Psalm: Static analisis tool made by Vimeo. It also has some detecting failures of security settings with a flag.

level 1 is the most strict, level 8 is the most lenient.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
12
Q

Que es Psalm y que significa (errorLevel=”3”)

A

Psalm: Static analisis tool made by Vimeo. It also has some detecting failures of security settings with a flag.

level 1 is the most strict, level 8 is the most lenient.
Open source

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
13
Q

Que es PHPStan y que significa (level: 7)

A

PHP Static Analysis Tool. PHPStan focuses on finding errors in your code without actually running it. It catches whole classes of bugs even before you write tests for the code. It moves PHP closer to compiled languages in the sense that the correctness of each line of the code can be checked before you run the actual line.

0 is the loosest, 9 is the strictest.
Open source

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
14
Q

Que es Rector,

A

composer require rector/rector –dev
vendor/bin/rector init
vendor/bin/rector –dry-run

Rector is a CLI tool written in PHP. It can instantly upgrade old PHP code and handle automated refactorings. It’s fast and precise - changes 5000 files under minute.

Open source

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
15
Q

Que es PHPCS,

A

PHP_CodeSniffer is a set of two PHP scripts; the main phpcs script that tokenizes PHP, JavaScript and CSS files to detect violations of a defined coding standard, and a second phpcbf script to automatically correct coding standard violations. PHP_CodeSniffer is an essential development tool that ensures your code remains clean and consistent.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
16
Q

Que es PHP-CS-Fixer,

A

The PHP Coding Standards Fixer (PHP CS Fixer) tool fixes your code to follow standards; whether you want to follow PHP coding standards as defined in the PSR-1, PSR-2, etc., or other community driven ones like the Symfony one. You can also define your (team’s) style through configuration.

It can modernize your code (like converting the pow function to the ** operator on PHP 5.6) and (micro) optimize it.

If you are already using a linter to identify coding standards problems in your code, you know that fixing them by hand is tedious, especially on large projects. This tool does not only detect them, but also fixes them for you.

17
Q

Que es PHPCS,

A

PHP_CodeSniffer is a set of two PHP scripts; the main phpcs script that tokenizes PHP, JavaScript and CSS files to detect violations of a defined coding standard, and a second phpcbf script to automatically correct coding standard violations. PHP_CodeSniffer is an essential development tool that ensures your code remains clean and consistent.
Open source

18
Q

Que es PHP-CS-Fixer,

A

The PHP Coding Standards Fixer (PHP CS Fixer) tool fixes your code to follow standards; whether you want to follow PHP coding standards as defined in the PSR-1, PSR-2, etc., or other community driven ones like the Symfony one. You can also define your (team’s) style through configuration.

It can modernize your code (like converting the pow function to the ** operator on PHP 5.6) and (micro) optimize it.

If you are already using a linter to identify coding standards problems in your code, you know that fixing them by hand is tedious, especially on large projects. This tool does not only detect them, but also fixes them for you.

OpenSource

19
Q

Que es Deptrac,

A

Deptrac is a static code analysis tool for PHP that helps you communicate, visualize and enforce architectural decisions in your projects. You can freely define your architectural layers over classes and which rules should apply to them.

For example, you can use Deptrac to ensure that bundles/modules/extensions in your project are truly independent of each other to make them easier to reuse.

Deptrac can be used in a CI pipeline to make sure a pull request does not violate any of the architectural rules you defined. With the optional Graphviz formatter you can visualize your layers, rules and violations.

Open source

20
Q

Que es phpcpd,

A

phpcpd is a Copy/Paste Detector (CPD) for PHP code.

21
Q

Que es ESLint

A

Find Problems

ESLint statically analyzes your code to quickly find problems. ESLint is built into most text editors and you can run ESLint as part of your continuous integration pipeline.
Fix Automatically

Many problems ESLint finds can be automatically fixed. ESLint fixes are syntax-aware so you won’t experience errors introduced by traditional find-and-replace algorithms.
Customize

Preprocess code, use custom parsers, and write your own rules that work alongside ESLint’s built-in rules. You can customize ESLint to work exactly the way you need it for your project.

22
Q

What is Prettier

A

An opinionated code formatter
Supports many languages
Integrates with most editors
Has few options

You press save and code is formatted
No need to discuss style in code review
Saves you time and energy

CSS, JS, HTML, GRAPHQL, YAML, MD, and community plugings, such as PHP

23
Q

What is Prettier

A

An opinionated code formatter
Supports many languages
Integrates with most editors
Has few options

You press save and code is formatted
No need to discuss style in code review
Saves you time and energy

CSS, JS, HTML, GRAPHQL, YAML, MD, and community plugings, such as PHP

Still a bit unstable for PHP

24
Q

Laravel Service container

A

Se usa entre otras cosas para el dependency injection,. Se puede usar a interfaces para tambien favorecer el testeo, si se inyecta un gateway se puede reemplazar con uno falso en un entorno de pruebas.

25
Q

Advantages to coding to actions or usecases

A

Other than just to avoid crowding the controllers, which must have as minimum ammount of code as possible, it’s also useful as to unit test portions of your code.

26
Q

JWT

A

JSON Web Token. Laravel Passport implementa JWT.

JSON Web Token is an open standard that defines a way of securely transferring data as a JSON object. JSON Web Tokens contain three parts: the header, the payload and the signature.

The header defines the type of token (in this case JWT) and the signing algorithm used.

The payload contains the “Claims”, these are typically information about the user (such as Name or User Permissions) and any other relevant information, and include details of when the token will expire.

The signature is generated by combining the header and payload and encoding them with the specified algorithm and secret key.

In a system with JWT configured, once a user signs in, a token is generated and returned to the user. The information is encoded using a key that is managed by the server (In Laravel you would typically store this in your dotenv file). Whenever a user then wishes to access the system, the user agent (a browser or app) will send the JWT to the server where it is decoded using the key, and if the details are correct, the user can the access the relevant resources on the server.

27
Q

Oauth2

A

OAuth 2.0 es un estándar abierto para la autorización de APIs, que nos permite compartir información entre sitios sin tener que compartir la identidad.

28
Q

CQRS

A

https://mevelix.com/articles/laravel-cqrs-from-scratch,1

Command Query Responsibility Segregation.

Se /separa/ el modelo en writing y reading.
En este patron arquitectural (que lo vi tambien en el articulo de arquitectura hexagonal: https://fideloper.com/hexagonal-architecture ) existen los commands y los queries. Los commands son de escritura, estamos hablando de un ‘CreateProductCommand’ y un ‘CreateProductCommandHandler’ y para las queries tenemos ‘ProductSimpleQuery’.

Tambièn se usa el CommandBus, que es el que resuelve  como usar el comando que se le pasa.
# command
$command = new CreateProductCommand($name, $price);
$this->commandBus->handle($command);
# query
$query = new ProductSimpleQuery($id);
return $query->getData();

Resuelve la problematica de que en apps grandes la escritura y lectura puede ser asimetrica con diferente performance y requerimientos de escalada

Bullet points de microsoft (https://docs.microsoft.com/en-us/azure/architecture/patterns/cqrs):

There is often a mismatch between the read and write representations of the data, such as additional columns or properties that must be updated correctly even though they aren't required as part of an operation.

Data contention can occur when operations are performed in parallel on the same set of data.

The traditional approach can have a negative effect on performance due to load on the data store and data access layer, and the complexity of queries required to retrieve information.

Managing security and permissions can become complex, because each entity is subject to both read and write operations, which might expose data in the wrong context.

Para ver cuando usar, mirar el mismo articulo de microsoft.

29
Q

Arquitectura Hexagonal

A

La arquitectura hexagonal busca desacoplar lo máximo posible el framework de la aplicación.

Se puede utilizar usando CQRS, que es una arquitectura que busca separar la lectura y la escritura del modelo. Utiliza Commands y command handlers para la escritura y Querys para la lectura. Usa un CommandBus para resolver los comandos que le tiran.

Las ventajas que ganan es en la implementación de practicas SOLID y en la posibilidad de usar patrones de diseño como el Decorator. Se vale mucho de los service container para lograr un binding entre la interfaz y la implementación de la interfaz

Tiene capas, de dominio, aplicacion e infraestructura, y cada capa se comunica solo con la capa superior.

Cada capa tiene codigo y tiene boundries o limites. El codigo es eso, codigo de funcionamiento del app. Los boundries son las maneras en las que la capa se comunica con la siguiente. En general, son interfaces. Por ejemplo, el commandbus puede ser una interfaz que vive en la boundary del dominio. La capa de aplicación utiliza esa interfaz y lo implementa como necesita.

Para arrancar a utilizar este tipo de patrones en Laravel, dentro de src se crean tres carpetas, dentro del application service container se hacen los bindings necesarios, en el composer json se agrega src al psr-4, y… se comienza!