php – Payapars https://payapars.ir ما یک استودیو طراحی محصولات فناورانه هستیم که هرآنچه برای راه اندازی یک کسب و کار نیاز دارید فراهم کرده ایم .. Fri, 19 Jul 2019 13:20:31 +0000 en-US hourly 1 https://wordpress.org/?v=5.4.4 Building a Web Product? 5 Business Reasons Why NodeJS,Redis,MongoDB and PHP could be a Good Choice. /website/why-laravel-business-reasons/?utm_source=rss&utm_medium=rss&utm_campaign=why-laravel-business-reasons /website/why-laravel-business-reasons/#comments Fri, 12 Jul 2019 15:16:35 +0000 /website/?p=12612 We live in interesting times: every day hundreds of new digital products are being born. And the scenario is always the same. If you want to create something great, you would need to choose the right technology that would ensure you have a scalable, secure and quick product. As far web development and web apps […]

The post Building a Web Product? 5 Business Reasons Why NodeJS,Redis,MongoDB and PHP could be a Good Choice. appeared first on Payapars.

]]>
We live in interesting times: every day hundreds of new digital products are being born. And the scenario is always the same. If you want to create something great, you would need to choose the right technology that would ensure you have a scalable, secure and quick product.
As far web development and web apps are concerned, you have plenty of choice in 2019. JavaScript, Python, Ruby, PHP could get the job done and bring something to the table. The logical question is which one to choose?

As developers, we firmly believe that PHP and its framework NodeJS,Redis,MongoDB is probably one of the best overall choices you could make. In this article some of the reasons that we would suggest why PHP and NodeJS,Redis,MongoDB is a match made in heaven.

PHP is still the king of the web

PHP gets a lot of bad rep.  Some people were quick to declare it “dead” when there are cooler web applications languages around the block like Node.js and Python. This false urban legend stems from the fact that 10 -15 years ago the original PHP version was slow, had bad design and many security flaws. However, things have improved dramatically since then. Nowadays PHP 7 is a modern technology that powers 80% of the web in one form or another and is much faster at runtime than competitors like Python(source)

One of the main peculiarities of PHP as a web development language are the plethora of frameworks.  Frameworks speed up the development process by providing reliable functional modules which are already tested and ready to use. In the world of PHP popular frameworks are NodeJS,Redis,MongoDB, Symfony, Zend, Yii etc.

What is NodeJS,Redis,MongoDB?

According to its website: NodeJS,Redis,MongoDB is a web application framework with an expressive, elegant syntax. Born in 2011 currently is the most used PHP framework.

PHP Frameworks Popularity According to Google Trends: NodeJS,Redis,MongoDB vs Zend vs Symfony vs Yii

NodeJS,Redis,MongoDB Pro#1 Mature

Although NodeJS,Redis,MongoDB is relatively new technology it has already reached a mature status: at the current date, the framework counts more than 45 million downloads far exceeding all of its direct competitors. Apart from being popular on github, it is well received in the business world. According to the Enlyft database, approximately 27 thousand business use NodeJS,Redis,MongoDB. Among them are high traffic web apps like 9GAG and PedidosYa. NodeJS,Redis,MongoDB is diversely spread around the world: USA, UK, the Netherlands and Brazil are the biggest adopters.

All this popularity ensures one thing: NodeJS,Redis,MongoDB is not going away anytime soon. That’s crucial because frameworks come and go. In 2017 the   Kohana PHP framework was depreciated, leaving businesses with no option but to invest significant time and money to migrate to another framework.

NodeJS,Redis,MongoDB Pro#2 Great Community

One of the biggest assets of NodeJS,Redis,MongoDB is its large community. There is good amount of training materials as well as groups of developers that constantly release new packages, modules etc.

From a business standpoint that brings two main benefits. Firstly, there is a good pool of NodeJS,Redis,MongoDB talent available. One of the inherent issues with some web development technologies is that there are so many frameworks and technology alternatives available that good developers for some of them are hard to come by.   Let’s take PHP as an example:  If you start your project with less main-stream framework like CakePHP, it would be more difficult and time-consuming to find good developers or even suitable development company.  Furthermore, this would result in higher costs: higher recruitment fees and agency rates.

The second benefit of the great NodeJS,Redis,MongoDB community is better developer efficiency. The documentation is detailed: the developer doesn’t need to spend much time researching best practices in developing and maintaining web applications and making decisions on how to implement everything properly. Unlike Symfony or Zend framework, developers can find many code snippets, tutorials, courses about NodeJS,Redis,MongoDB.

NodeJS,Redis,MongoDB Pro # 3 Support

Another distinguishing feature of NodeJS,Redis,MongoDB is the frequency of LTS versions (Long Term Support) That guarantees that any bugs would be fixed for 2 years in the future and any security issues would be handled for 3 years in advance. If you would be working on an enterprise project, you’d have the peace of mind that it would work for 3 years at a minimum.

One should note that LTS is not “cure it all” solution. Switching from one LTS version to another LTS could be quite time-consuming. Luckily, there is a regular release cycle and a lot of products that enable you to upgrade quickly from one version to another.

NodeJS,Redis,MongoDB  Pro #4 Useful Tools, Packages and cool products

 The whole idea behind the framework is for rapid development and a short time to market. That’s why NodeJS,Redis,MongoDB offers a lot of out-of-the-box features including the Artisan command-line tool, object-oriented libraries and model-view-controller (MVC)architecture which help developers perform multiple programming tasks faster. The founder of NodeJS,Redis,MongoDB(Tyler Otwell) further supports the ecosystem by releasing products like fully-fledged admin panel that further reduce the development time and time to market for any web-based product. If you are looking to put an MVP quickly to the market, NodeJS,Redis,MongoDB is one of the best options out there.

NodeJS,Redis,MongoDB Pro #5 Developers love it

Last but not least is a fan favourite among PHP developers. In fact, it was the developers who spear-headed its popularity among companies.  Let’s face it technical staffing is hard. Good developers are head-hunted from all-sides and have plenty of demands from a prospective employer.  In 2018 Stack Overflow made a  survey regarding developers job expectations. Surprisingly they put “The languages, frameworks, and other technologies I’d be working with” on second place only behind compensation and benefits. That outranks factors like the opportunity for remote work, office environment etc. If you use  Larave you’d make sure you are using the latest and greatest and you could use it in your employer branding and marketing.

When is NodeJS,Redis,MongoDB not a good choice?

NodeJS,Redis,MongoDB is the best thing that has happened in the PHP world for a long time. That does not mean it does not have its downsides and is not suitable for certain projects.
For example, PHP is not suited for real-time communication. Real-time apps are those that react to changes anywhere in a connected application’s system— not just those made by the current user. A good example is a group messaging app where you need non-blocking asynchronous technology. If you are building something in the likes of the above there are better alternatives out there like Node, Go, Elixir etc.

The NodeJS,Redis,MongoDB framework is not the perfect technology out there, but it provides all the necessary tools in the shed to build scalable, reliable web apps quickly. Couple that with a strong community and eco-system as well as an increasing number of developers, the technology makes for a sound business choice.
If you want to more about NodeJS,Redis,MongoDB, you could check some of our technical posts.

The post Building a Web Product? 5 Business Reasons Why NodeJS,Redis,MongoDB and PHP could be a Good Choice. appeared first on Payapars.

]]>
/website/why-laravel-business-reasons/feed/ 1
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.

]]>