web development – Payapars https://payapars.ir ما یک استودیو طراحی محصولات فناورانه هستیم که هرآنچه برای راه اندازی یک کسب و کار نیاز دارید فراهم کرده ایم .. Sun, 28 Apr 2019 19:05:37 +0000 en-US hourly 1 https://wordpress.org/?v=5.4.4 Null Object Pattern in NodeJS,Redis,MongoDB /website/null-object-pattern-laravel/?utm_source=rss&utm_medium=rss&utm_campaign=null-object-pattern-laravel Fri, 28 Sep 2018 12:28:18 +0000 /website/?p=11194 How to use Null Object Pattern in NodeJS,Redis,MongoDB to deal with deleted relation or missing property of an API response

The post Null Object Pattern in NodeJS,Redis,MongoDB appeared first on Payapars.

]]>
Null Object Pattern in NodeJS,Redis,MongoDB
There are many times when we take for granted the relations in our database or some fields in an external API, CSV file or other data source. And in such situations, we often receive some kind of NullPointerException.
NodeJS,Redis,MongoDB with its convenient ORM, might bring us in such troubles unless we are careful. Imagine a simple blog site where you have users who can write posts and you display the author’s name under the title. With NodeJS,Redis,MongoDB, you just write $post->author->name, pretty cool right? But what happens when the author deletes his account. You might consider one of the following:
  • Delete all user’s posts, but why losing such useful information without a valid reason?
  • Denormalize the posts table and save some of the user information there, for example, the name, so you never need to worry, if the user is there.
  • Use soft deletes and never delete the user, but this might be a problem with the new GDPR regulations. Furthermore, you need to remember to load the relation with the trashed records. You can fix these problems if on delete you rename the user to “Unknown” and assign them a random email and password, but this is logic write.
  • Create a method on the blog post class which returns the author’s name, where you check for its existence and return some sensible default.
As you can see, there are a lot of possible solutions and depending on the case you might need some of them or even another one which is not listed here. But I would like to present you an alternative, that you can use when you think you need it.

Defining the Null Object Pattern

The Null Object Pattern is a design pattern, where some function/method returns an object or literal, that should act as a “null” version of the expected one. You can read more on Wikipedia about it. A simple example might be a function, that should return an array of items, which you want to filter, map over its items or just pass it into foreach. But what happens when there are no items to return? You might return null, but now you need to check, every time before performing, that foreach loop. The null object alternative would be to return an empty array and skip the check, just run the foreach.

If you are using such techniques, you are implementing the pattern, so congrats on that.

 Examples from the framework

You can find the pattern implemented in many places in the framework. Some examples are the get() method of the Models, which always returns Collection, no matter if there are records or not, or the magic methods of the models, which allows you to access not existing properties. But more interesting are the methods, that allows you to specify, your own version of the null value. Here are some examples of such methods:

Default relations

You can specify a default value to be returned, on the “to one” relations, as they would return null by default. This is done via the withDefault() method when defining the relation, which can even accept an array of params to make the model with, so it has some sensible defaults. If you don’t pass anything when no User is found, empty one will be returned.
class Post extends Model
{
     public function author()
     {
         return $this->belongsTo(User::class)->withDefault([
             'name' => 'Unknown Author',
         ]);
     }
}
Now we can call $post->author->name, without worrying if there is a user, and when a user deletes its account we can just delete it.
Of course, there are other solutions to the problem and you can argue if the default name should be specified in the relation method, or in some method for determining the author’s name. Here is how it might look using the ?? operator:
class Post extends Model
{
    public function author()
    {
        return $this->belongsTo(User::class);
    }

    public function authorName()
    {
        return $this->user->name ?? 'Unknown Author';
    }
}
Bellow, I will describe some other functions which utilize the null object pattern across the framework.

Array and object accessors

They are really useful, when dealing with responses from other systems, reading files, accepting requests or every time you are not sure that the value will be there. There are two functions array_get and object_get for the different types of data structures. You should use array_get for associative arrays, no matter that object_get seems logical there. Here are 2 quick examples for both of them:
  • object_get($cloth, ‘brand’, ‘unknown brand’) – returns the brand property of the cloth object, if such exists, or unknown brand
  • array_get($colors, ‘black’, ‘000000’) – returns the value for black key of the colors array, or our default black value
  • another option is to simply use the ?? operator, which was introduced in php7, and simplify the code, even more,  $colors[‘black’] ?? ‘000000’
Of course, you can use them without the default values and they will return null but will prevent exceptions about not defined indexes and items.

Request get method

You can call the get() method on the $request object to receive the value of some input field, but it also accepts a second parameter, which is the default value returned, when the property does not exist. So $request->get(‘wants_emails’, false) return the value of wants_emails or false, if such is not defined. It could be also used with the request(‘wants_emails’, false) function if you prefer to use it.

Custom classes

Sometimes you might want to create “null” classes, which mimics the methods of real implementation, but does “null”. You can implement all methods of the mimicked class or just a handful of them. This might be especially helpful in tests to replace some object. Another place to use the pattern might be when you have many similar classes and you don’t want to break the flow with null checks. If you create a class, that is instantiated in the null case, you can use it like the others and not clutter the code with null checks. In those cases, you can even implement common interfaces, if you are into it since it is a real class.

Bonus:

The optional() helper is another function, which helps to deal with nulls in the code, even tho it does not provide a way to specify a default value. Here is a little example where it can save us from unexpected exceptions, optional($user->address)->city. This way we will receive null even when there is no address property on the user class.
In conclusion, I hope that the next time you are wondering, how to deal with the possibility, of deleted relation or missing property of an API response, you would have one more weapon in your arsenal and don’t have to write if statement, because nobody likes them.
Our team specialises in PHP development, you could find us on PHP Development companies directory

The post Null Object Pattern in NodeJS,Redis,MongoDB appeared first on Payapars.

]]>
Handling Complicated Requests In NodeJS,Redis,MongoDB /website/handling-complicated-requests-laravel/?utm_source=rss&utm_medium=rss&utm_campaign=handling-complicated-requests-laravel Tue, 10 Jul 2018 09:43:40 +0000 /website/?p=11155 How to deal with forms/requests on the web efficiently using NodeJS,Redis,MongoDB

The post Handling Complicated Requests In NodeJS,Redis,MongoDB appeared first on Payapars.

]]>
Description of the problem

Dealing with forms/requests on the web is one of the toughest problems to solve in the modern web, and as developers, we always seek ways to handle it in a more elegant way. But for education purposes most of the tutorials, we read/watch online, teach us how to deal with only simple requests. So that when we stumble upon some complicated request with 20 fields, which should create 5 types of models, we just don’t know what to do and dump all the logic in the controller.

This is a problem with the MVC architecture in general because it does not teach us where to put the complicated logic.

Let’s see some example of such complicated request, which we will be using in the post to address the problems and provide you with my solution.

It again is simplified version of what really is possible, but I think is enough to explain the concept.

Example for a complicated request

Let’s pretend we have an app where we have vehicles and we can create requests for parts for them, so someone can send us the needed parts. Here is the Object that we have:

  • Vehicle – description of our car/motorcycle
  • Request – Links the parts to vehicle and author
  • Part – Description of the part needed, each request can contain more that one part
public function store(IlluminateRequest $request)
{
$requestData = $request->validate([
'name' => ['required', 'string', 'min:3'],
'vehicle' => ['required', 'numeric', 'exists:vehicles,id'],
'parts' => ['required', 'array'],
'parts.*.name' => ['required', 'string', 'min:2'],
'parts.*.description' => ['required', 'string', 'min:6'],
'parts.*.oem_number' => ['nullable', 'string', 'min:6'],
]);

$partsRequest = Request::create([
'name' => $requestData['name'],
'vehicle_id' => $requestData['vehicle'],
'user_id' => $request->user()->id,
]);

$parts = array_map(function ($partData) {
return Part::make($partData);
}, $requestData['parts']);

$partsRequest->parts()->saveMany($parts);

return redirect()->route('requests.index');
}

After we saw the code and understand the domain let’s explore some methods to simplify it.

TL;DR: You can jump straight to Form requests to the rescue if you don’t want to read my other solutions and what I think about them.

Possible solutions which are not always The Solution (Private methods, Service classes, Commands)

Long and hairy controller methods

This is always a valid approach to do the work, especially when you don’t plan to revisit this method or controller, but since you are reading this article, you think you need a better approach, so let’s continue with the other options.

Private methods in the controller

This is maybe the best place to start. I like this approach because it keeps the logic in one class even though this is the controller. But we have some problems with this approach:

  • the number of controller methods grow, which might be a problem, when we have 4-5 or more public methods and try to create some private ones for them
  • as these are controller methods they do not have access to the request data, as it belongs to the request object, and we should pass it from method to method. This makes such methods more like plain functions, which is always something to consider when deciding where to put a method.

Create a Dedicated Service classes

The Service classes are something like an extension to the MVC architecture in some frameworks, but I personally don’t like them, because they are just one more buzzword. Don’t know where to put the logic, dump it into a Service Class, or worse, create a Service Class for each controller method.
Another problem with service classes is when you need to return a view from the controller with more than one variable/model/data source. In this case, we should return may be an associative array from the service class (which is practically the response), which in my opinion is a bit problem, because the service class takes the responsibility of the controller.
Of course, if we use them wisely they might be beneficial in some cases because we will have something like the approach with private methods in the controller, but without the problems. If we pass the request to the constructor, then we will be able to use its data in all the private methods of the service class, which solves the problems outlined in using private methods.
In our particular example, this approach might just do the job perfectly, but I think we can think of a better solution.

Commands

The problem with the whole Commands for saving Repositories for fetching concept, to me is that it is too complicated and overwhelming. In most of the cases simple Model::create([…]) and Model::where(…)->get() work just fine.
Of course, the whole CQRS architecture has its place under the sun, but I definitely don’t think, we should go for it without really needing it.

Form requests to the rescue

As we know NodeJS,Redis,MongoDB provides us with Form Request objects, which can be automatically injected in the controller method, and handle the validation and authorization logic of the request, so this can simplify our code a bit. The thing I don’t like here is, that we basically move the array of rules in another class and the validate method is called automatically for us, which is not enough to me. I want the form request to earn its existence. And also the ugly part of the work (the remapping of request fields to model fields) is still in the controller, which is really the thing, that bugs me.

public function store(CreatePartsRequest $request)
{
$partsRequest = Request::create([
'name' => $requestData['name'],
'vehicle_id' => $requestData['vehicle'],
'user_id' => $request->user()->id,
]);

$parts = array_map(function ($partData) {
return Part::make($partData);
}, $requestData['parts']);

$partsRequest->parts()->saveMany($parts);

return redirect()->route('requests.index');
}

So one thing we can do here is to move the mapping part of the code into some descriptive methods on the Form Request so it finally has more work to do to justify its existence and the code becomes much cleaner in my eyes.

The controller code

public function store(CreatePartsRequest $request)
{
$partsRequest = Request::create($request->requestParams());
$parts = $request->parts()->map([Part::class, 'make']);
$partsRequest->parts()->saveMany($parts);

return redirect()->route('requests.index');
}

The form request code

public function rules()
{
return [
'name' => ['required', 'string', 'min:3'],
'vehicle' => ['required', 'numeric', 'exists:vehicles,id'],
'parts' => ['required', 'array'],
'parts.*.name' => ['required', 'string', 'min:2'],
'parts.*.description' => ['required', 'string', 'min:6'],
'parts.*.oem_number' => ['nullable', 'string', 'min:6'],
];
}

public function requestParams()
{
return [
'name' => $this->get('name'),
'vehicle_id' => $this->get('vehicle'),
'user_id' => $this->user()->id,
];
}

public function parts()
{
return collect($this->get('parts', []));
}

With this approach we can handle transformations between HTML forms and DB/models format, switch between conventions (camelCase in js to snake_case in PHP/DB), selecting database records to fill some missing data, extracting other request info, or any other data when needed.
Last but not least, I don’t recommend this approach for each form on your project. Use it only when you need to store more models or have complicate request data massaging.
I even don’t recommend using NodeJS,Redis,MongoDB’s Form Request classes just for validation, do it straight in the controller.

The post Handling Complicated Requests In NodeJS,Redis,MongoDB appeared first on Payapars.

]]>
Thoughts from the CTO: Introduction to PHPUnit code coverage reports /website/phpunit-code-coverage-reports/?utm_source=rss&utm_medium=rss&utm_campaign=phpunit-code-coverage-reports Mon, 19 Mar 2018 16:03:15 +0000 /website/?p=11006 How to have code coverage reports with PHP and succeed in Test Driven Development.

The post Thoughts from the CTO: Introduction to PHPUnit code coverage reports appeared first on Payapars.

]]>
Recently we finished a green field project written in PHP with NodeJS,Redis,MongoDB as a framework, that was carried out under the Test Driven Development methodology right from the start.
Test Driven Development is the preferred way of building high quality and scalable software. The biggest benefit is the ability to change the requirements and implementation and having a short feedback loop, of that if something went wrong.
We decided to check its code coverage at the end, to have some idea about the number of tests we have and how much of the code they cover.
After some research, it turned out, that it is pretty simple.
You just need to have xdebug enabled and it will do all the heavy lifting.

Enabling xdebug for testing

If you are not sure, if you have xdebug enabled follow this paragraph, else you can proceed with the phpunit.xml update.
Run php –ini to find your xdebug configuration file. Mine is located in /usr/local/etc/php/7.0/conf.d/ext-xdebug.ini
It should look like following snippet, if it is working.

zend_extension="/usr/local/opt/php70-xdebug/xdebug.so"
xdebug.remote_enable = 1
xdebug.remote_autostart = 1

After turning on xdebug, you don’t need to restart anything as we will be running the tests from the console.

Phpunit configuration

Since xdebug will do all the work, just add the following lines to your phpunit.xml file. I’ve added them below the listener’s tag.

<logging>
<log type="”coverage-clover”" target="”tests/_reports/logs/clover.xml”/">
<log type="”coverage-html”" target="”tests/_reports/coverage”" charset="”UTF-8″" yui="”true”" highlight="”true”" lowupperbound="”35″" highlowerbound="”70″">
<log type="”testdox-text”" target="”tests/_reports/testdox/executed.txt”/">
</log></log></log></logging>

You might comment on this section in development mode and use it only when you want to generate a new report.

Preparing the code coverage report

To prepare the report just run phpunit in you project and wait for it to finish the execution.
You should be patient, because it was more than 6 times slower for my project, than the normal run of the tests with xdebug enabled.
Finally, the results should appear in tests/_reports/coverage, where you will find index.html file, which you can use to start browsing your test coverage report.

Tips on tests speed

– If you are not a debugger just disable xdebug and your test suite will run so much faster (in my case around 4 times faster).
– If you are using NodeJS,Redis,MongoDB and its authentication system during tests, decrease the encryption algorithm complexity only for you tests, by adding the following line to your createApplication method located in tests\CreatesApplication trait, to make them run even faster (2x performance boost for me).

 Hash::setRounds(4); 

– You might use johnkary/phpunit-speedtrap to report you which tests are running slow, so you can try to improve them.
– Finally this one is not speed related, but I really like it codedungeon/phpunit-result-printer. You might install this package to change the way executed tests are presented in the console.

If you are in need of help with PHP/NodeJS,Redis,MongoDB/ development our team could support you: drop us a line!

The post Thoughts from the CTO: Introduction to PHPUnit code coverage reports appeared first on Payapars.

]]>