When to use Controller Class Properties in Laravel
I wanted to talk a little about what properties are and also methods in this case focused on the controllers here in larbel since at least it is a very personal opinion but when we are using the methods here:
public function registerBook(Book $book, string $orderId, string $payment = "paypal")
{
$user = $this->getUser();
if ($user == null) {
return $this->errorResponse("", 202, 'Usuario no encontrado, no se hizo ningun cargo a tu cuenta');
}
if ($book->isFree(request("coupon"))) {
return $this->registerBookToUser(
$book,
***
);
}
// registra el libro
return $this->registerBookToUser(
$book,
***
);
}
That we define them to resolve a request is what I call and I think they are called controller functions or controller methods, whatever you want to call them, because in the end, what is really the controller is the method in which we have multiple methods in a controller. Maybe I know a little bit about the approach or the bases that they are.
Classes, properties, inheritance, traits…
What is this, this is a class with all the advantages that this brings us in a very summarized way and what could be most used is the inheritance part that we are already extending here with the Trades that this is like multiple inheritance, you could say a kind of multiple inheritance that we have here in php and also another great neglected thing is the use of properties that can also make our lives much easier and…
Right now I want to talk to you a little about what I had and how I was able to solve it, so the simplest way to use the properties before going into detail with all this that I have here I think it would be this one that I have here called the base URL, the first thing I also want to tell you is that I still have to improve this code more, for example here you can see that some I defined the type here I did not define it because this is multiple and I have an existential conflict there and here I did not even define a type, I am not
saying that it is the best code, I simply want to exemplify my example, excuse the redundancy here, the simplest would be this one here I have the URLs:
By the way, so that you can get into context, in the purchasing part of my platform, this is precisely where I am also placing the strike and that is why you see references to strike here in the code. I have not yet launched it into production, but anyway, it is basically this and this is if you have followed my course, you know how it works. It is so that, from the server, once the order is obtained here on the client, which is what is generated, you can see if it is valid and finish processing it. In other words, when the payment is made to the client, it is done on the server. At least that is how it works in PayPal. In strike, things change a little:
class BasePaymentController extends Controller
{
protected $clientId;
protected $secret;
protected $baseURL = 'https://api-m.paypal.com';
public function __construct()
{
$this->baseURL = config('app')['env'] == 'local' ? 'https://api-m.sandbox.paypal.com' : 'https://api-m.paypal.com';
$this->clientId = config('app')['paypal_id'];
$this->secret = config('app')['paypal_secrect'];
}
}
But that is another story here we are generating the URL that can be two, the sandbox one that would be for test mode that I have here for reference and this one that is the one we use in production in the end also this URL as I told you is used to make requests to PayPal and that is why I reference it in this way to be able to use it easily throughout the application where it is used to generate the token and also to verify the payment and finally collect it and that is why you see and to initialize it and that is why you see this in this way this is a simple way as they say and useful to use the properties since they are used in multiple methods that is the important part the constructor is to initialize here we use it in the case of controllers is so that every time a method is called it is also every time a method is called for example of a controller it is also initialized, that is to say it is being like a kind of middleware that is executed before making the request and in this case it is to reinitialize key aspects such as the secret keys And in this case also the base URL of PayPal in which I take the sandbox if I am in a development and production environment if I am well in a production environment that would be the other case that I handle here then for the rest this URL is used internally in the controller methods in this case not directly because I call this method from the controllers to make it more modularized but in essence ex that if we look for it This is a method no this no good is that this is the base sorry because I am also doing this class from another part this I would call it here in this s request Api that the end I call it in the controller it is a little nested and it is that I am trying to modularize enough and finally I call it here that this is a controller it does not matter here the bifurcation but in the end it is called from a controller and in the end how everything works it is always done here the base URL as I told you this is a simple case because it is simply a component and you can easily see that it is necessary to use this base URL in multiple parts of the application but here there is also one a little more interesting or more or less the same but it changes a little and it was precisely for What job do I have here? In this case, this is for payment information about what is happening when we are processing the order. This would be for the price, that is, when the payment is being made. I like to obtain this information from the API response. In this case, we are talking about PayPal:
class BasePaymentController extends Controller
{
protected int|float $price = 0;
protected string $status = '';
protected string $idAPI = ''; // es el ordenId pero para manejar en la fun
protected array|object $responseAPI;
protected string $payment = 'paypal';
protected function sendRequestAPI(string $orderId)
{
if ($orderId == 'stripe') {
// stripe
$this->responseAPI = $this->checkPayedSession(request("stripe_session_id"));
if ($this->responseAPI->payment_status == 'paid') {
$this->status = 'COMPLETED';
$this->idAPI = request("stripe_session_id");
$this->payment = 'stripe';
//dd($this->responseAPI);
$this->price = intdiv($this->responseAPI->amount_total, 100);
} else {
// respuesta error stripe excepcion
return $this->errorResponse("", 202, json_encode($this->responseAPI));
}
} else {
// paypal
$this->responseAPI = $this->processPayPayPal($orderId);
if (isset($this->responseAPI['status']) && $this->responseAPI['status'] == 'COMPLETED') {
$this->status = 'COMPLETED';
$this->idAPI = $this->responseAPI['id'];
$this->price = $this->responseAPI['purchase_units'][0]['payments']['captures'][0]['amount']['value'];
}
}
}
But it is also the same for stripe, which is the payment platform used and main or stripe? This is for internal control, this would be the identifier, that is, the order ID in PayPal and the session ID in stripe and this would be the status if it was completed and in the case of stripe, I think it is payed:
// stripe
$this->responseAPI->payment_status == 'paid'
//paypal
isset($this->responseAPI['status']) && $this->responseAPI['status'] == 'COMPLETED'
So, there are several elements that are common that we want to manage globally, such as price, status, platform, among others, and when using different payment platforms, they can be unified through a method that does the conversion for us and we establish them in properties so that we can use them transparently and regardless of the platform.
There are several verifications in one place and it is precisely this method that modularizes what this method does that was common in those three operations, then first it verifies what the hell is the payment book that you are using if PayPal or stripe because in both cases, that is, the payment plugin is the same for all cases, therefore here I am verifying which one you are using is stripe or PayPal
Again, the main problem here is that we have two types of answers, one is from Stripe and the other is from PayPal, but surely in the future another platform can be added, let's say Mercado Pago, anything that occurs to me, but in the end, the important thing is to notice that regardless of the platform that I use, I can schematize it precisely with the structure that I defined previously.
I agree to receive announcements of interest about this Blog.
I comment on a couple of scenarios in which I consider the properties in the Controllers in Laravel to be useful.
- Andrés Cruz