PHP & Web Development Blogs

Search Results For: framework
Showing 6 to 10 of 15 blog articles.
8975 views · 4 years ago
When PHP Frameworks Suck

INTRO

If you are working as a PHP software developer, there is an extremely high chance that all of your application, you’re currently working on, using frameworks of any kind.
PHP community developers of all levels worship frameworks since there are big historical and practical reasons for that.

Historical reasons

Since early PHP versions, developers were disreputable because not everybody considered PHP as a programming language, similar to JavaScript a couple of years ago. While strong type language existed decades ago, PHP continues to be soft type since now, only in version 7 basic types were introduced. There is also a matter of the fact that you can script in PHP without using a single object.

But that opened a space for frameworks to step in and introduce themselves as a tool or standard which will shape projects, give them right and order, introduce structure and rules.
And finally, they did. Frameworks are good examples of nice structures, using all available new features PHP offers with every version, enforcing some good practice, etc.

Practical reasons

The framework offers a lot of common problems already solved. They offer a nice ecosystem for other developers to contribute and plug their components. There is a lot of online resources for learning and stay updated about any particular framework. Also, what every framework community tries very hard, is to make setup and usage easy.

WHEN PHP FRAMEWORKS SUCKS

I recently had the opportunity to give a talk on a conference and one meetup about why PHP framework sometimes sucks. Sometimes things we see in framework tutorials does not seem to be very much aligned with some object-oriented standards we are striving to enforce, and with basic clean code guidelines. On the other hand, there is nothing wrong with using a framework, if you use it right.

This article is the first "pilot" article in this series. In every new blog in this series, we will go more in-depth about every specific topic I covered during my presentation.
I'm very excited to share this knowledge, as I saw many developers suffer from bonded-to-framework disease.

https://twitter.com/damnjan/status/1058306144458956800

I won’t spend much time here on any particular framework discussion. This series will be just a guide on how to unbind yourself from frameworks and use them as a tool, instead of being independent.

**Here is the link to the presentation slides.**
9604 views · 5 years ago
Conferences are always looking for speakers - it can be hard to keep track of them all and the requirements they have. I wanted to put together this quick guide to make it easy for you to apply. Make sure to apply because as Wayne Gretzky said “You miss 100% of the shots you don’t take”!!!

phpDay 2019

First we have phpDay 2019 which will take place on May 10 & 11 at Hotel San Marco in Verona, Italy. Some facts about this call for papers:
*Submission deadline: February 4, 2019
*Submit via: https://cfp.phpday.it/
* For more info on the conference: https://2019.phpday.it/
* Twitter: (@phpday)
* Speaker package includes: Full conference pass (jsDay + phpDay), speaker dinner the first night, lunch, reception and activities included in regular conference.
* For speakers remote to the Area: A refund of up to €200 for travel costs (or €500 from US or extra-EU), 2 complimentary hotel nights (+1 hotel night for speakers presenting multiple talks or US/extra-EU) and Taxi fare from/to the airport.
*In Submission: make sure your talk title and abstract define the exact topic you want to talk about and what you hope people will learn from the session.
*Talk Ideas: APIs (REST, SOAP, etc.), Architectures, Continuous Delivery, Databases, Development, Devops, Frameworks, Internals, PHP 7.x / PHP 8, Security, Testing and UI/UX.

ScotlandPHP

Next we have ScotlandPHP which will take place on November 8 & 9 at Edinburgh International Conference Centre in Edinburgh, Scotland.
*Submission deadline: April 22, 2019
*Submit via: https://cfs.scotlandphp.co.uk/
* For more info on the conference: https://conference.scotlandphp.co.uk/
* Twitter: (@scotlandphp)
* Speaker package: Full conference pass, lunch, receptions and activities included in regular conference.
* For speakers remote to the Area: Complimentary airfare/travel, 2 complimentary hotel nights and we'll pick you up and drop you off to/from the airport so you don't have to worry about it.
* Speakers will be provided with a projector, a wireless lapel microphone and a screen for their presentation (size depends on the room). Speakers should bring any equipment they need to connect to projectors (VGA). It is also suggested that you reduce your dependency on the in-house internet connection as possible. We will however provide HDMI and Mini Display Port connections for all speakers on request. If you need something different or your selected talk needs audio equipment just let us know. We'll work it out.
* Looking for talks and workshops (November 8th).
*Talk Ideas: Virtualization and environments, Javascript, Alternate PHP run-times, PHP internals, Development principles, Security, Mobile-first design, Testing (unit, functional, etc.), Version control, User Experience/Usability, Building APIs (REST, SOAP, whatever), Continuous Integration, Framework-related topics, and Professional development.

Global diversity CFP day

In 2019 there will be numerous workshops hosted around the globe encouraging and advising newbie speakers to put together your very first talk proposal and share your own individual perspective on any subject of interest to people in tech.
* Twitter: (@gdcfpday)
*Save the Date: March 2, 2019
*Register here: https://www.globaldiversitycfpday.com/?utm_source=scotphp

CoderCruise

Then there is CoderCruise which will take place on August 19-23. It's a cruise that takes off from Port Canaveral, Florida and goes to the Bahamas.
* Twitter: (@codercruise)
*Submission deadline: March 3, 2019
*Submit via: https://www.papercall.io/codercruise-2019
* For more info on the conference: https://www.codercruise.com/
* This is a polyglot conference so looking for speakers on a wide variety of languages (PHP, JavaScript, Java, Python, etc.) and on various tech topics.

PHP Conference Asia 2019

There is also PHP Conference Asia 2019, which will take place on June 24-25 at Microsot Singapore.
*Submission deadline: March 8, 2019
*Submit via: https://cfp.phpconf.asia/
* For more info on the conference: https://2019.phpconf.asia/
* Twitter: (@PHPConfAsia)
* Speaker package includes: Speaker package: Full conference pass, lunch, receptions and activities included in regular conference. We'll pick you up and drop you off to/from the airport so you don't have to worry about it. Speakers' dinner on the first evening of the conference (24th June 2019). Transport to and from the conference venue will be included
* For speakers remote to the Area: 2 complimentary hotel nights and
we can consider providing grants to partially cover the air-fare for speakers who might have financial difficulties. This is on a case-by-case basis.
* Speakers will be provided with a projector, a wireless hand-held microphone and a screen for their presentation. Speakers should prepare their slides in 4x3 aspect ratio. Speakers should bring any equipment they need to connect to projectors (HDMI). It is also suggested that you reduce your dependency on the in-house internet connection as possible.
*In Submission: Make sure your talk title and abstract define the exact topic you want to talk about and what you hope people will learn from the session.
*Talk Ideas: Virtualization and environments, Javascript, Alternate PHP run-times, PHP internals, Development principles, Security, Mobile-first design, Testing (unit, functional, etc.), Version control, User Experience/Usability, Building APIs (REST, SOAP, whatever), Continuous Integration, Framework-related topics, and Professional development.

Cascadia PHP

Another conference to apply to is Cascadia PHP, which will take place on September 19-21 at University Place Hotel & Conference Center in Portland, Oregon.
*Submission deadline: April 15, 2019
*Submit via: https://cfp.cascadiaphp.com/
* For more info on the conference: https://www.cascadiaphp.com/venue
* Twitter: (@CascadiaPHP)
* Speaker package includes: Speaker package: Full conference pass, lunch, receptions and activities included in regular conference. For speakers remote to the Area: Complimentary airfare/travel, 2 complimentary hotel nights and we'll pick you up and drop you off to/from the airport so you don't have to worry about it.
Speakers will be provided with a projector, a wireless lapel microphone and a screen for their presentation (size depends on the room). Speakers should bring any equipment they need to connect to projectors (VGA). It is also suggested that you reduce your dependency on the in-house internet connection as possible.
*In Submission: make sure your talk title and abstract define the exact topic you want to talk about and what you hope people will learn from the session.
*Talk Ideas: PHP internals, Version control, Framework-related topics, Building APIs (REST, SOAP, whatever), Mobile-first design, Professional development, Testing (unit, functional, etc.), Alternate PHP run-times, Development principles, Continuous Integration, Getting involved in the PHP community, User Experience/Usability, Technology at large, Security, Connecting to Different APIs, Development Tools, Virtualization and environments, Javascript, Modern hosting practices, Language Features, Databases, Refactoring legacy applications, Running/contributing to open source projects, AI and AR, and User Groups.

Nomad PHP

Last but not least - this is an ongoing call for papers. This is perfect if you want to present from the comfort of your office, home or really wherever you are. It’s via RingCentral meetings and will be live and recorded. This is for none other than Nomad PHP.
* Twitter: (@nomadphp)
* Deadline: Anytime :D
* Talk length: 45 - 60 minutes.
* Talks should be unique to Nomad PHP and not available in video format online.
* Talk should not be recorded or made available elsewhere online for at least 3 months following your talk.
* The talk will be featured on our page and promoted via social media.
* Speakers will receive a financial stipend.
* Upon being selected we will reach out with further details.
*Talk ideas: AI & Machine Learning, APIs, Containerization, Databases, DevOps, Documentation, Frameworks, Performance, Security, Serverless, Testing, Tools, Upgrading/ Modernization, and more.
*Submit here: https://www.papercall.io/nomadphp
Now that you have some information - make sure to apply to all of these options! Can't wait to see all of your awesome talks you present :D!
12998 views · 5 years ago
Working With Thin Controller And Fat Model Concept In Laravel

Models and controllers are one of the most essential programming handlers in the Laravel MVC framework, and both are used vastly for different functional operations. Models in Laravel are created inside the app folder and are mostly used to interact with the database using Eloquent ORM, while the controllers are located inside the directory App/Http/Controllers.

As a programmer, you should have the knowledge how to keep the balance in between the programming usage of Models and controllers. As which one should be more utilized for allowing functional tasks in applications deployed on any PHP MySQL hosting.


What is the Concept of Thin Controller and FAT Models


The concept of the thin controller and fat model is that we do less work in our controllers and more work in our models. Like we use our controllers to validate our data and then pass it to the models. While in models, we define our actual functional logic and main coding operations of the desired application. This code structuring process is also a very basic concept of MVC and also the differentiating factor from the conventional complex programming which we mistakenly ignore sometimes.


Why FAT Controllers Are Bad For Handling Code


Controllers are always meant to be defined short and concise, and it should only be used for receiving requests and return responses to it. Anything else further should be programmed in Models, which is actually made for main functional operations.

Placing functional logic in controllers can be bad for many reasons for your applications deployed on anyhosting for PHP. As it not only makes code structure long but also makes it complex sometimes. Further placing code in Controllers is also not recommended because if same functionality is needed somewhere else in route, then pulling out the whole code from their becomes difficult and so its reusability in the application.

Though Laravel is an MVC framework while developing on laravel, we sometimes ignore this and write mostly all our code including the extending of App\Model and all our functional logic in controller route methods. What we can do here is we can create a sub model of our parent model. For example, our parent model is User then we can create another sub model of username in CustomerModel if you are using the same User model for all types of users. In this model, we will write all the logic related to user type Customer.

So now let's take an example of my existing blog creating comment system with laravel and vuejs. In that article, you can see I have made so much mess in my controller methods. Mostly, I have written all my comments logic in my methods, so to shorten that let's clean them in this article. Inside app folder, I will create a new file with name CommentModel.php. Inside this file, I will write my whole logic for comment functions. This is my basic file:


<?php
namespace App;

use App\Comment;
use App\CommentVote;
use App\CommentSpam;
use App\User;
use Auth;

class CommentModel
{


}

?>



Right now it contains no function but has the reference of all my models which I required for this model. Let's first add a function namedgetallcomments passing$pageId as a parameter inside it. The function will get all the comments for the given page:


public function getAllComments($pageId)
{
$comments = Comment::where('page_id',$pageId)->get();

$commentsData = [];


foreach ($comments as $key) {
$user = User::find($key->users_id);
$name = $user->name;
$replies = $this->replies($key->id);
$photo = $user->first()->photo_url;
$reply = 0;
$vote = 0;
$voteStatus = 0;
$spam = 0;
if(Auth::user()){
$voteByUser = CommentVote::where('comment_id',$key->id)->where('user_id',Auth::user()->id)->first();
$spamComment = CommentSpam::where('comment_id',$key->id)->where('user_id',Auth::user()->id)->first();


if($voteByUser){
$vote = 1;
$voteStatus = $voteByUser->vote;
}

if($spamComment){
$spam = 1;
}
}


if(sizeof($replies) > 0){
$reply = 1;
}

if(!$spam){
array_push($commentsData,[
"name" => $name,
"photo_url" => (string)$photo,
"commentid" => $key->id,
"comment" => $key->comment,
"votes" => $key->votes,
"reply" => $reply,
"votedByUser" =>$vote,
"vote" =>$voteStatus,
"spam" => $spam,
"replies" => $replies,
"date" => $key->created_at->toDateTimeString()
]);
}


}
$collection = collect($commentsData);
return $collection->sortBy('votes');
}



Now I will create another function namedreplies which takes$commentId as a parameter. The function is more or less programmed in the same manner as the upper function get all comments.


protected function replies($commentId)
{
$comments = Comment::where('reply_id',$commentId)->get();
$replies = [];



foreach ($comments as $key) {
$user = User::find($key->users_id);
$name = $user->name;
$photo = $user->first()->photo_url;

$vote = 0;
$voteStatus = 0;
$spam = 0;


if(Auth::user()){
$voteByUser = CommentVote::where('comment_id',$key->id)->where('user_id',Auth::user()->id)->first();
$spamComment = CommentSpam::where('comment_id',$key->id)->where('user_id',Auth::user()->id)->first();

if($voteByUser){
$vote = 1;
$voteStatus = $voteByUser->vote;
}

if($spamComment){
$spam = 1;
}
}
if(!$spam){


array_push($replies,[
"name" => $name,
"photo_url" => $photo,
"commentid" => $key->id,
"comment" => $key->comment,
"votes" => $key->votes,
"votedByUser" => $vote,
"vote" => $voteStatus,
"spam" => $spam,
"date" => $key->created_at->toDateTimeString()
]);
}




}


$collection = collect($replies);
return $collection->sortBy('votes');
}



Now lets create a functioncreate comment which passes$array as a parameter in it:


public function createComment($arary)
{
$comment = Comment::create($array);


if($comment)
return [ "status" => "true","commentId" => $comment->id ];
else
return [ "status" => "false" ];
}



Similarly, Now I will create all the function for comment in myCommentModel, so that all the functions gets accumulated in one model.


<?php
namespace App;

use App\Comment;
use App\CommentSpam;
use App\CommentVote;
use App\User;
use Auth;

class CommentModel
{
public function getAllComments($pageId)
{
$comments = Comment::where('page_id', $pageId)->get();

$commentsData = [];

foreach ($comments as $key) {
$user = User::find($key->users_id);
$name = $user->name;
$replies = $this->replies($key->id);
$photo = $user->first()->photo_url;
$reply = 0;
$vote = 0;
$voteStatus = 0;
$spam = 0;
if (Auth::user()) {
$voteByUser = CommentVote::where('comment_id', $key->id)->where('user_id', Auth::user()->id)->first();
$spamComment = CommentSpam::where('comment_id', $key->id)->where('user_id', Auth::user()->id)->first();

if ($voteByUser) {
$vote = 1;
$voteStatus = $voteByUser->vote;
}

if ($spamComment) {
$spam = 1;
}
}

if (sizeof($replies) > 0) {
$reply = 1;
}

if (!$spam) {
array_push($commentsData, [
"name" => $name,
"photo_url" => (string) $photo,
"commentid" => $key->id,
"comment" => $key->comment,
"votes" => $key->votes,
"reply" => $reply,
"votedByUser" => $vote,
"vote" => $voteStatus,
"spam" => $spam,
"replies" => $replies,
"date" => $key->created_at->toDateTimeString(),
]);
}

}
$collection = collect($commentsData);
return $collection->sortBy('votes');
}

protected function replies($commentId)
{
$comments = Comment::where('reply_id', $commentId)->get();
$replies = [];

foreach ($comments as $key) {
$user = User::find($key->users_id);
$name = $user->name;
$photo = $user->first()->photo_url;

$vote = 0;
$voteStatus = 0;
$spam = 0;

if (Auth::user()) {
$voteByUser = CommentVote::where('comment_id', $key->id)->where('user_id', Auth::user()->id)->first();
$spamComment = CommentSpam::where('comment_id', $key->id)->where('user_id', Auth::user()->id)->first();

if ($voteByUser) {
$vote = 1;
$voteStatus = $voteByUser->vote;
}

if ($spamComment) {
$spam = 1;
}
}
if (!$spam) {

array_push($replies, [
"name" => $name,
"photo_url" => $photo,
"commentid" => $key->id,
"comment" => $key->comment,
"votes" => $key->votes,
"votedByUser" => $vote,
"vote" => $voteStatus,
"spam" => $spam,
"date" => $key->created_at->toDateTimeString(),
]);
}

}

$collection = collect($replies);
return $collection->sortBy('votes');
}

public function createComment($arary)
{
$comment = Comment::create($array);

if ($comment) {
return ["status" => "true", "commentId" => $comment->id];
} else {
return ["status" => "false"];
}

}

public function voteComment($commentId, $array)
{
$comments = Comment::find($commentId);
$data = [
"comment_id" => $commentId,
'vote' => $array->vote,
'user_id' => $array->users_id,
];

if ($array->vote == "up") {
$comment = $comments->first();
$vote = $comment->votes;
$vote++;
$comments->votes = $vote;
$comments->save();
}

if ($array->vote == "down") {
$comment = $comments->first();
$vote = $comment->votes;
$vote--;
$comments->votes = $vote;
$comments->save();
}

if (CommentVote::create($data)) {
return true;
}

}

public function spamComment($commentId, $array)
{
$comments = Comment::find($commentId);

$comment = $comments->first();
$spam = $comment->spam;
$spam++;
$comments->spam = $spam;
$comments->save();

$data = [
"comment_id" => $commentId,
'user_id' => $array->users_id,
];

if (CommentSpam::create($data)) {
return true;
}

}
}
?>



Now we have all our required methods inCommentModel. So now let's clean upCommentController which is currently bit complex and lengthy in code structure. As right nowCommentController look like this:


<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Http\Requests;
use App\Comment;
use App\CommentVote;
use App\CommentSpam;
use App\User;
use Auth;

class CommentController extends Controller
{



public function index($pageId)
{
$comments = Comment::where('page_id',$pageId)->get();

$commentsData = [];




foreach ($comments as $key) {
$user = User::find($key->users_id);
$name = $user->name;
$replies = $this->replies($key->id);
$photo = $user->first()->photo_url;
$reply = 0;
$vote = 0;
$voteStatus = 0;
$spam = 0;
if(Auth::user()){
$voteByUser = CommentVote::where('comment_id',$key->id)->where('user_id',Auth::user()->id)->first();
$spamComment = CommentSpam::where('comment_id',$key->id)->where('user_id',Auth::user()->id)->first();


if($voteByUser){
$vote = 1;
$voteStatus = $voteByUser->vote;
}

if($spamComment){
$spam = 1;
}
}


if(sizeof($replies) > 0){
$reply = 1;
}

if(!$spam){
array_push($commentsData,[
"name" => $name,
"photo_url" => (string)$photo,
"commentid" => $key->id,
"comment" => $key->comment,
"votes" => $key->votes,
"reply" => $reply,
"votedByUser" =>$vote,
"vote" =>$voteStatus,
"spam" => $spam,
"replies" => $replies,
"date" => $key->created_at->toDateTimeString()
]);
}


}
$collection = collect($commentsData);
return $collection->sortBy('votes');
}

protected function replies($commentId)
{
$comments = Comment::where('reply_id',$commentId)->get();
$replies = [];



foreach ($comments as $key) {
$user = User::find($key->users_id);
$name = $user->name;
$photo = $user->first()->photo_url;

$vote = 0;
$voteStatus = 0;
$spam = 0;


if(Auth::user()){
$voteByUser = CommentVote::where('comment_id',$key->id)->where('user_id',Auth::user()->id)->first();
$spamComment = CommentSpam::where('comment_id',$key->id)->where('user_id',Auth::user()->id)->first();

if($voteByUser){
$vote = 1;
$voteStatus = $voteByUser->vote;
}

if($spamComment){
$spam = 1;
}
}
if(!$spam){


array_push($replies,[
"name" => $name,
"photo_url" => $photo,
"commentid" => $key->id,
"comment" => $key->comment,
"votes" => $key->votes,
"votedByUser" => $vote,
"vote" => $voteStatus,
"spam" => $spam,
"date" => $key->created_at->toDateTimeString()
]);
}




}


$collection = collect($replies);
return $collection->sortBy('votes');
}


public function store(Request $request)
{
$this->validate($request, [
'comment' => 'required',
'reply_id' => 'filled',
'page_id' => 'filled',
'users_id' => 'required',
]);
$comment = Comment::create($request->all());
if($comment)
return [ "status" => "true","commentId" => $comment->id ];
}


public function update(Request $request, $commentId,$type)
{
if($type == "vote"){


$this->validate($request, [
'vote' => 'required',
'users_id' => 'required',
]);

$comments = Comment::find($commentId);
$data = [
"comment_id" => $commentId,
'vote' => $request->vote,
'user_id' => $request->users_id,
];

if($request->vote == "up"){
$comment = $comments->first();
$vote = $comment->votes;
$vote++;
$comments->votes = $vote;
$comments->save();
}

if($request->vote == "down"){
$comment = $comments->first();
$vote = $comment->votes;
$vote--;
$comments->votes = $vote;
$comments->save();
}

if(CommentVote::create($data))
return "true";
}

if($type == "spam"){


$this->validate($request, [
'users_id' => 'required',
]);

$comments = Comment::find($commentId);


$comment = $comments->first();
$spam = $comment->spam;
$spam++;
$comments->spam = $spam;
$comments->save();

$data = [
"comment_id" => $commentId,
'user_id' => $request->users_id,
];

if(CommentSpam::create($data))
return "true";
}
}


public function destroy($id)
{
}
}?>



After cleaning up the controller it will look much simpler and easy to understand like this:


<?php

namespace App\Http\Controllers;

use App\CommentModel;
use Illuminate\Http\Request;

class CommentController extends Controller
{

private $commentModel = null;
private function __construct()
{
$this->commentModel = new CommentModel();
}


public function index($pageId)
{
return $this->commentModel->getAllComments($pageId);
}


public function store(Request $request)
{
$this->validate($request, [
'comment' => 'required',
'reply_id' => 'filled',
'page_id' => 'filled',
'users_id' => 'required',
]);
return $this->commentModel->createComment($request->all());
}


public function update(Request $request, $commentId, $type)
{
if ($type == "vote") {

$this->validate($request, [
'vote' => 'required',
'users_id' => 'required',
]);

return $this->commentModel->voteComment($commentId, $request->all());
}

if ($type == "spam") {

$this->validate($request, [
'users_id' => 'required',
]);

return $this->commentModel->spamComment($commentId, $request->all());
}
}

}
?>




Wrap Up!


So Isn't it looking much cleaner and simpler to understand now? This is what actually a thin controller and fat model looks like. We have all our logic related to Comment system programmed in ourCommentModel and our controller is now just used to transfer data from the user to our model and returning the response which is coming from our model.

So this is how the structuring of the thin controller and fat model is made. Give your thoughts in the comments below.
6749 views · 5 years ago
Custom extension to Laravel Application class

Hello folks! This post is for those of you using Laravel. This beautiful framework makes web development super-easy compared to most of competitors. In the heart of Laravel is the Application class, which is responsible for bootstrapping, registering services and also serves as a dependency injection container. What I do with my Laravel apps, is that I take a slight detour from the common path by adding a custom Application class. While this is not really necessary, I find this approach nice, and will try to share my thought below.

It's normal practice in Laravel world to build all kinds of objects like this:

$cache = app("cache");


I find it a bit confusing to call app("cache"") and expect a Cache\Repository instance as result. If I pass the result of this call to a function that requires a Cache\Repository as parameter, I will probably have a code inspection warning from IDE. Moreover, if I want proper autocompletion, I will have to add additional comment:


$cache = app("cache");


This is where a custom application class might be handy:

namespace App;
class MyApp extends Application
{
public function cacheRepository(): Repository
{
return $this->make(Repository::class);
}
}


This way I get a TypeError in case of a misconfiguration, and I have a type-hint which allows the IDE to recognize the return value. Bye-bye nasty comment lines and IDE warnings! I make a method per service, with type-hints, like dbConnection() or viewFactory() - works really well for me!

I also thought that, if I have a custom class, then all the custom setup that normally you have in bootstrap/app.php, should reside in that custom class:

namespace App;
class MyApp extends Application
{
public function __construct()
{
define('LARAVEL_START', microtime(true));
define("APP_ROOT", realpath(__DIR__ . "/../"));
parent::__construct(APP_ROOT);
$this->setUp();
}
private function setUp()
{
$this->singleton(
Contracts\Http\Kernel::class,
\App\Http\Kernel::class
);
}
}


Then your bootstrap/app.php becomes just this:

return new \App\MyApp;


The Laravel app() function will also return an instance of MyApp from now on. However, it's @phpdoc says it returns \Illuminate\Foundation\Application, so for better clarity, I also added my own accessor method:

namespace App;
class MyApp extends Application
{
public static function app(): self
{

$ret = parent::getInstance();
return $ret;
}
}


I tend to limit the use of global/static functions and methods, but sometimes it can be handy, and whenever I need an instance of MyApp, I just call MyApp::app(). The IDE wil be aware of the return type due to the type-hint, so I get everything I want for clean and clear development.

With your projects in Laravel, you may or may not want to follow this particular advice, but just be aware that extending a framework built-in classes for your team's comfort, is definitely something that can make your life easier. See you around, don't forget to leave comments!
7610 views · 5 years ago
Iterator in PHP

Every time I see this
$users = [new User(), new User()];

I see a lost opportunity to use Iterator.

Why Iterators?

Collections are an awesome way to organize your previously no-named array. There is a couple of reasons why you should use iterators. One of reason stays for behavior, you can specify exact behavior on standard calls such as next, current, valid etc. Other reason could be that you want to ensure that collection contains an only specific type of an object.

Understand a suffer from using an array of unknown value types.
Very common in the PHP world arrays are used to store all kind of data, in many dimensions in many nested forms. Arrays introduced infinite flexibility to the developer, but because of that, they become very evil.

Example:

- Your function (getUsers) returns an array of User objects.
- Another function (setUsersToActiveState) using getUsers output array and set all users active status to true.
- setUsersToActiveState loop through the array and expect to call a specific method on array item. For example, the method name is getActiveStatus.
- If given array is an array of desired objects which have a callable method getActiveStatus, all fine. But if not exception will be thrown.
- How we can ensure that given array is always an array of objects of a specific type?

public function getUsers(): array
{

return $userArray;
}

public function setUsersToActiveState()
{
$users = $this->getUsers();

foreach ($users as $user) {
if(!$user->getActiveStatus()) {
$user->setActiveStatus(true);
}
}
}

There immediately two problems occurred.
    . One is the problem of type. Our IDE doesn't know what's inside array of $users, so because of that IDE can't suggest us how to use $user element. (I put this comment block above foreach, it works for phpStorm and I guess for some other IDEs)
    . Your colleagues! How they possibly know what's inside array if there is no any hint.
    . Bonus problem, getUsers can return literally any array and there won't be warning in the system.

Solution



class UsersCollection implements \IteratorAggregate
{

private $users = [];

public function getIterator() : UserIterator
{
return new UserIterator($this);
}

public function getUser($position)
{
if (isset($this->users[$position])) {
return $this->users[$position];
}

return null;
}

public function count() : int
{
return count($this->users);
}

public function addUser(User $users)
{
$this->users[] = $users;
}
}

class UserIterator implements \Iterator
{

private $position = 0;


private $userCollection;

public function __construct(UsersCollection $userCollection)
{
$this->userCollection = $userCollection;
}

public function current() : User
{
return $this->userCollection->getUser($this->position);
}

public function next()
{
$this->position++;
}

public function key() : int
{
return $this->position;
}

public function valid() : bool
{
return !is_null($this->userCollection->getUser($this->position));
}

public function rewind()
{
$this->position = 0;
}
}

Tests

Off course there is the tests to ensure that our Collection and Iterator works like a charm. For this example I using syntax for PHPUnit framework.

class UsersCollectionTest extends TestCase
{

public function testUsersCollectionShouldReturnNullForNotExistingUserPosition()
{
$usersCollection = new UsersCollection();

$this->assertEquals(null, $usersCollection->getUser(1));
}


public function testEmptyUsersCollection()
{
$usersCollection = new UsersCollection();

$this->assertEquals(new UserIterator($usersCollection), $usersCollection->getIterator());

$this->assertEquals(0, $usersCollection->count());
}


public function testUsersCollectionWithUserElements()
{
$usersCollection = new UsersCollection();
$usersCollection->addUser($this->getUserMock());
$usersCollection->addUser($this->getUserMock());

$this->assertEquals(new UserIterator($usersCollection), $usersCollection->getIterator());
$this->assertEquals($this->getUserMock(), $usersCollection->getUser(1));
$this->assertEquals(2, $usersCollection->count());
}

private function getUserMock()
{
}
}


class UserIteratorTest extends MockClass
{

public function testCurrent()
{
$iterator = $this->getIterator();
$current = $iterator->current();

$this->assertEquals($this->getUserMock(), $current);
}


public function testNext()
{
$iterator = $this->getIterator();
$iterator->next();

$this->assertEquals(1, $iterator->key());
}


public function testKey()
{
$iterator = $this->getIterator();

$iterator->next();
$iterator->next();

$this->assertEquals(2, $iterator->key());
}


public function testValidIfItemInvalid()
{
$iterator = $this->getIterator();

$iterator->next();
$iterator->next();
$iterator->next();

$this->assertEquals(false, $iterator->valid());
}


public function testValidIfItemIsValid()
{
$iterator = $this->getIterator();

$iterator->next();

$this->assertEquals(true, $iterator->valid());
}


public function testRewind()
{
$iterator = $this->getIterator();

$iterator->rewind();

$this->assertEquals(0, $iterator->key());
}

private function getIterator() : UserIterator
{
return new UserIterator($this->getCollection());
}

private function getCollection() : UsersCollection
{
$userItems[] = $this->getUserMock();
$userItems[] = $this->getUserMock();

$usersCollection = new UsersCollection();

foreach ($userItems as $user) {
$usersCollection->addUser($user);
}

return $usersCollection;
}

private function getUserMock()
{
}
}


Usage


public function getUsers(): UsersCollection
{
$userCollection = new UsersCollection();

foreach ($whatIGetFromDatabase as $user) {
$userCollection->addUser($user);
}
return $userCollection;
}

public fucntion setUsersToActiveState()
{
$users = $this->getUsers();

foreach ($users as $user) {
if(!$user->getActiveStatus()) {
$user->setActiveStatus(true);
}
}
}

As you can see setUsersToActiveState remains the same, we only do not need to specify for our IDE or collagues what type $users variable is.

Extending functionalities

Believe or not you can reuse this two objects and just change names of variables to fit most of the needs. But if you want any more complex functionality, than feel free to add it in iterator or collection.

Example 1


For example, let's say that userCollection accepts only users with age more than 18. Implementation will happen in UsersCollection class in the method addUser.

 public function addUser(User $users)
{
if ($user->getAge() > 18) {
$this->users[] = $users;
}
}

Example 2

You need to add bulk users. Then you can expand your userCollection with additional method addUsers and it might look like this.

public function addUsers(array $users)
{
foreach($users as $user) {
$this->addUser(User $users);
}
}

SPONSORS