PHP & Web Development Blogs

Search Results For: development
Showing 11 to 15 of 21 blog articles.
10969 views · 3 years ago


It took me quite some time to settle on my first blog post in this series and I found myself thinking about the most requested functionality in my career – The good ‘ol Custom CMS – typically geared towards clients that want a straight forward, secure solution that can be expanded upon in a modular format and that’s their IP.

This will be our starting point. A blank slate to build something epic with clean code and even cleaner design. And in the spirit of building from scratch, I will refrain from using classes or a framework. The main reasoning behind this is to truly get everyone acquainted with and excited about PHP development.

Join me as I transform rudimentary code into something extraordinary that can be morphed into just about any Content, PHP, and MySQL driven project. So without further ado, let’s jump into it!

The bare necessities


If you’re just getting started with development, there’s a nifty bite sized server called UniformServer that will be your best friend throughout your coding career. PHPMyAdmin (an awesome visual db management tool) comes built in so if you’re looking for a work right out of the box solution, this is it.

Alternatively, you can opt for XAMPP or use an alternative server of your choice.

Now here’s where the exciting stuff begins, mapping things out.


I don’t see this done/encouraged often enough. Feel free to grab a piece of paper to logically map out your steps or produce a rough draft of where you’d like this project to go.

In this tutorial, I would like to achieve the following:



DB, DB, Set up your DB.


This requires a bit of planning but let’s start of with the basic structure we need to see this through.

We are going to need a user table and a content table and are a few ways to tackle this.

If you’re using the PHPMyAdmin tool you can create your database, add user permissions (Click on Permissions after creating your database), and create a table with ease.



If you’re like me and prefer to look at good ‘ol SQL then writing an SQL statement is the preferred approach.


CREATE TABLE <code>mydbname</code>.<code>content</code> ( <code>ID</code> INT(11) NOT NULL AUTO_INCREMENT , <code>title</code> VARCHAR(100) NOT NULL , <code>content</code> LONGTEXT NOT NULL , <code>author</code> VARCHAR(50) NOT NULL , PRIMARY KEY (<code>ID</code>)) ENGINE = MyISAM COMMENT = 'content table';


Understanding the SQL statement

In a nutshell we are creating a table with important fields. Namely:

####

ID | Title | Content | Author

#######

The ID field is our unique identifier.Now we can move on to the file structure.

Everything has a place in the file structure game


You can use a structure that speaks to your coding style / memory.

I tend to use the following:



Choose a name for your CMS, which should be placed at the webroot of your localhost/server.

Replicate the folder structure as per the above example.

Next, we’re going to create a basic connection file.


You can create a conn.php file in your root/includes folder.

The connection file will provide crucial information to connect to the database.

Type the following into your conn.php file, remember to include your own database credentials.


<?php

$letsconnect = new mysqli("localhost","dbuser","dbpass","dbname");

?>


Let’s go to the homepage (index.php)


Create a file called index.php at the root of your CMS folder.

I will be adding comments in my code to help you understand what each line does.

Comments are a useful tool for developers to add important notes private to their code.

We need to pull information from the database so it’s imperative that we include our connection file.


<?php

include('includes/conn.php');

if ($letsconnect -> connect_errno) { echo "Error " . $letsconnect -> connect_error;

}else{

$getmydata=$letsconnect -> query("SELECT * FROM content");

foreach($getmydata as $mydata){ echo "Title: "; echo $mydata['title']; echo "<br/>"; echo "Content: "; echo $mydata['content']; echo "<br/>"; echo "Author: "; echo $mydata['author']; echo "<br/>"; echo "<br/>";

}

}

$letsconnect -> close();

?>


Let’s get a (very) basic backend up and running


Create a file called index.php in your backend folder.

We need to create a basic form to capture our data.

Let’s code some HTML!


<html>

<head><title>Backend - Capture Content</title></head>

<body>

<form action="<?php $_SERVER[‘PHP_SELF’];?>" method="post">

<input type="text" name="title" placeholder="Content Title here" required/>

<textarea name="content">Content Here</textarea>

<input type="text" name="author" placeholder="Author" required/>

<input type="submit" value="Save My Data" name="savedata"/>

</form>

</body>

</html>


Next, we need to process the form data.


Type the following just above the
<form> 
tag.


<?php

if(isset($_POST['savedata'])){

include('../includes/conn.php');

if ($letsconnect->connect_error) {

die("Your Connection failed: " . $letsconnect->connect_error);

}else{

$sql = "INSERT INTO content(title,content,author)VALUES ('".$_POST["title"]."', '".$_POST["content"]."', '".$_POST["author"]."')";

if (mysqli_query($letsconnect, $sql)) {

echo "Your data was saved successfully!";

} else { echo "Error: " . $sql . "" . mysqli_error($letsconnect);

} $letsconnect->close();

}

}

?>


Note, this is a basic MySQL query to insert data. However, before using this in production it's important to add proper escaping and security to prevent SQL injections. This will be covered in the next article.


Congrats you made it to the end of tutorial 1!


Test out your creation, modify your content, and play around.

Go to your sitename/index.php to see your frontend after capturing data via sitename/backend/index.php

Next Up:


codewithme Now With Security, Functionality, and Aesthetics in mind.


Conclusion


Coding doesn’t have to be daunting and it’s my aim to divide a complex system into bitesized tutorials so you can truly use the knowledge you’ve acquired in your own projects.
12812 views · 4 years ago
Why Cloudways is the Perfect Managed Hosting for PHP Applications

The following is a sponsored blogpost by Cloudways


Developing an application is not the sole thing you should bank on. You must strive to find the best hosting solution to deploy that application also. The application’s speed is dependent on the hosting provider, that is why I always advise you to go for the best hosting solution to get the ultimate app performance.

Now a days, it is a big challenge to choose any web hosting, as each hosting has its own pros and cons which you must know, before considering it finally for the deployment. I don’t recommend shared hosting for PHP/Laravel based applications, because you always get lot of server hassles like downtime, hacking, 500 errors, lousy support and other problems that are part and parcel of shared hosting.

For PHP applications, you must focus on more technical aspects like caching, configs, databases, etc. because these are essential performance points for any vanilla or framework-based PHP application. Additionally, if the app focuses on user engagement (for instance, ecommerce store), the hosting solution should be robust enough to handle spikes in traffic.

Here, I would like to introduce Cloudways PHP server hosting to you which provides easy, developer and designer friendly managed hosting platform. With Cloudways, you don't need to focus on PHP hosting, but must focus on building your application. You can easily launch cloud servers on five providers including DigitalOcean, Linode, Vultr, AWS and GCE.


Cloudways ThunderStack


Being a developer, you must be familiar with the concept of stack - an arrangement of technologies that form the underlying hosting solution.

To provide a blazing fast speed and a glitch-free performance, Cloudways has built a PHP stack, known as ThunderStack. This stack consists of technologies that offer maximum uptime and page load speed to all PHP applications. Check out the following visual representation of ThunderStack and the constituent technologies:


alt_text


As you can see, ThunderStack comprises of a mix of static and dynamic caches with two web servers, Nginx and Apache. This combination ensures the ultimate experience for the users and visitors of your application.


Frameworks and CMS


The strength and popularity of PHP lies in the variety of frameworks and CMS it offers to the developers. Realizing this diversity, Cloudways offers a hassle-free installation of major PHP frameworks including Symfony, Laravel, CakePHP, Zend, and Codeigniter. Similarly, popular CMS such as WordPress, Bolt, Craft, October, Couch, and Coaster CMS - you can install these with the 1-click option. The best part is that if you have a framework or CMS that is not on the list, you can easily install it through Composer.


1-Click PHP Server & Application Installation


Setting up a stack on an unmanaged VPS could take an entire day!

When you opt for Cloudways managed cloud hosting, the entire process of setting up the server, installation of core PHP files and then the setup of the required framework is over in a matter of minutes.

Just sign up at Cloudways, choose your desired cloud provider, and select the PHP stack application.


alt_text


As you can see, your LAMP stack is ready for business in minutes.

Many PHP applications fail because essential services are either turned off or not set up properly. Cloudways offers a centralized location where you can view and set the status of all essential services such as:



* Apache
* Elasticsearch
* Memcached
* MySQL
* PHP-FPM
* Nginx
* New Relic
* Redis
* Varnish


alt_text


Similarly, you can manage SMTP add-ons without any fuss.


Staging Environment


With Cloudways, you can test your web applications for possible bugs and errors before taking it live.

Using the staging feature, developers can first deploy their web sites on test domains where they can analyze the applications performance and potential problems. This helps site administrators to fix those issues timely and view the application performance in real-time.

A default sub domain comes pre-installed with the newly launched application, making it easy for the administrators to test the applications on those testing subdomains. Overall, it's a great feature which helps developers know about the possible errors that may arise during the live deployment.

alt_text

Pre-Installed Composer & Git


PHP development requires working with external libraries and packages. Suppose you are working with Laravel and you need to install an external package. Since Composer has become the standard way of installing packages, it comes preinstalled on the Cloudways platform. Just launch the application and start using Composer in your project.

Similarly, if you are familiar with Git and maintain your project on GitHub or BitBucket, you don’t need to worry about Git installation. Git also comes pre-configured on Cloudways. You can start running commands right after application launch.


Cloudways MySQL Manager


When you work with databases in PHP, you need a database manager. On the Cloudways platform, you will get a custom-built MySQL manager, in which you can perform all the tasks of a typical DB manager.

alt_text


However, if you wish to install and use another database manager like PHPMyAdmin, you can install it by following this simple guide on installing PHPMyadmin.


Server & Application Level SSH


If you use Linux, you typically use SSH for accessing the server(s) and individual applications. A third-party developer requires application and server level access as per the requirements of the client. Cloudways offers SSH access to fit the requirements of the client and users.

alt_text


PHP-FPM, Varnish & Cron Settings


Cloudways provides custom UI panel to set and maintain PHP-FPM and Varnish settings. Although the default configuration is already in place, you can easily change all the settings to suit your own, particular development related requirements. In Varnish settings, you can define URL that you want to exclude from caching. You can also set permissions in this panel.

alt_text


Cron job is a very commonly used component of PHP application development process. On Cloudways platform, you can easily set up Cron jobs in just a few clicks. Just declare the PHP script URL and the time when the script will run.

alt_text


Cloudways API & Personal Assistant Bot


Cloudways provides an internal API that offers all important aspects of the server and application management. Through Cloudways API, you can easily develop, integrate, automate, and manage your servers and web apps on Cloudways Platform using the RESTful API. Check out some of the use cases developed using Cloudways API. You just need your API key and email for authentication of the HTTP calls on API Playground and custom applications.

alt_text


Cloudways employs a smart assistant named CloudwaysBot to notify all users about server and application level issues. CloudwaysBot sends the notifications on pre-approved channels including email, Slack and popular task management tools such as Asana and Trello.


Run Your APIs on PHP Stack


Do you have your own API which you want to run on the PHP stack? No problem, because you can do that, too with Cloudways! You can also use REST API like Slim, Silex, Lumen, and others. You can use APIs to speed up performance and require fast servers with lots of resources. So, if you think that your API response time is getting slower due to the large number of requests, you can easily scale your server(s) with a click to address the situation.


Team Collaboration


When you work on a large number of applications with multiple developers, you need to assign them on any specific application. Cloudways provides an awesome feature of team collaboration through which you can assign developers to specific application and give access to them. You can use this tool to assign one developer to multiple applications. Through team feature, you can connect the team together and work on single platform. Access can be of different type; i.e. billing, support and console. You can either give the full access or a limited one by selecting the features in Team tab.

alt_text


Final Words


Managed cloud hosting ensures that you are not bothered by any hosting or server related issues. For practical purposes, this means that developers can concentrate on writing awesome code without worrying about underlying infrastructure and hosting related issues. Do sign up and check out Cloudways for the best and the most cost-effective cloud hosting solution for your next PHP project!
11882 views · 5 years ago
Five Composer Tips Every PHP Developer Should Know

Composer is the way that that PHP developers manage libraries and their dependencies. Previously, developers mainly stuck to existing frameworks. If you were a Symfony developer, you used Symfony and libraries built around it. You didn’t dare cross the line to Zend Framework. These days however, developers focus less on frameworks, and more on the libraries they need to build the project they are working on. This decoupling of projects from frameworks is largely possible because of Composer and the ecosystem that has built up around it.

Like PHP, Composer is easy to get started in, but complex enough to take time and practice to master. The Composer manual does a great job of getting you up and running quickly, but some of the commands are involved enough so that many developers miss some of their power because they simply don’t understand.

I’ve picked out five commands that every user of Composer should master. In each section I give you a little insight into the command, how it is used, when it is used and why this one is important.

1: Require

Sample:

$ composer require monolog/monolog


Require is the most common command that most developers will use when using Composer. In addition to the vendor/package, you can also specify a version number to load along with modifiers. For instance, if you want version 1.18.0 of monolog specifically and never want the update command to update this, you would use this command.

$ composer require monolog/monolog:1.18.0


This command will not grab the current version of monolog (currently 1.18.2) but will instead install the specific version 1.18.0.

If you always want the most recent version of monolog greater than 1.8.0 you can use the > modifier as shown in this command.

$ composer require monolog/monolog:>1.18.0


If you want the latest in patch in your current version but don’t want any minor updates that may introduce new features, you can specify that using the tilde.

$ composer require monolog/monolog:~1.18.0


The command above will install the latest version of monolog v1.18. Updates will never update beyond the latest 1.18 version.

If you want to stay current on your major version but never want to go above it you can indicate that with the caret.

$ composer require monolog/monolog:^1.18.0


The command above will install the latest version of monolog 1. Updates continue to update beyond 1.18, but will never update to version 2.

There are other options and flags for require, you can find the complete documentation of the command here.

2: Install a package globally

The most common use of Composer is to install and manage a library within a given project. There are however, times when you want to install a given library globally so that all of your projects can use it without you having to specifically require it in each project. Composer is up to the challenge with a modifier to the require command we discussed above, global. The most common use of this is when you are using Composer to manage packages like PHPUnit.

$ composer global require "phpunit/phpunit:^5.3.*"


The command above would install PHPUnit globally. It would also allow it to be updated throughout the 5.0.0 version because we specified ~5.3.* as the version number. You should be careful in installing packages globally. As long as you do not need different versions for different projects you are ok. However, should you start a project and want to use PHPUnit 6.0.0 (when it releases) but PHPUnit 6 breaks backwards compatibility with the PHPUnit 5.* version, you would have trouble. Either you would have to stay with PHPUnit 5 for your new project, or you would have to test all your projects to make sure that your Unit Tests work after upgrading to PHPUnit 6.

Globally installed projects are something to be thought through carefully. When in doubt, install the project locally.

3: Update a single library with Composer

One of the great powers of Composer is that developers can now easily keep their dependencies up-to-date. Not only that, as we discussed in tip #1, each developer can define exactly what “up-to-date” means for them. With this simple command, Composer will check all of your dependencies in a project and download/install the latest applicable versions.

$ composer update


What about those times when you know that a new version of a specific package has released and you want it, but nothing else updated. Composer has you covered here too.

$ composer update monolog/monolog


This command will ignore everything else, and only update the monolog package and it’s dependencies.

It’s great that you can update everything, but there are times when you know that updating one or more of your packages is going to break things in a way that you aren’t ready to deal with. Composer allows you the freedom to cherry-pick the packages that you want to update, and leave the rest for a later time.

4: Don’t install dev dependencies

In a lot of projects I am working on, I want to make sure that the libraries I download and install are working before I start working with them. To this end, many packages will include things like Unit Tests and documentation. This way I can run the unit Tests on my own to validate the package first. This is all fine and good, except when I don’t want them. There are times when I know the package well enough, or have used it enough, to not have to bother with any of that.

Many packages create a distribution package that does not contain tests or docs. (The League of Extraordinary Packages does this by default on all their packages.) If you specify the --prefer-dist flag, Composer will look for a distribution file and use it instead of pulling directly from github. Of course if you want want to make sure you get the full source and all the artifacts, you can use the --prefer-src flag.

5: Optimize your autoload

Regardless of whether you --prefer-dist or --prefer-source, when your package is incorporated into your project with require, it just adds it to the end of your autoloader. This isn’t always the best solution. Therefore Composer gives us the option to optimize the autoloader with the --optimize switch. Optimizing your autoloader converts your entire autoloader into classmaps. Instead of the autoloader having to use file_exists() to locate a file, Composer creates an array of file locations for each class. This can speed up your application by as much as 30%.

$ composer dump-autoload --optimize


The command above can be issued at any time to optimize your autoloader. It’s a good idea to execute this before moving your application into production.

$ composer require monolog/monolog:~1.18.0 -o


You can also use the optimize flag with the require command. Doing this every time you require a new package will keep your autoloader up-to-date. That having said, it’s still a good idea to get in the habit of using the first command as a safety net when you roll to production, just to make sure.

BONUS: Commit your composer.lock

After you have installed your first package with composer, you now have two files in the root of your project, composer.json and composer.lock. Of the two, composer.lock is the most important one. It contains detailed information about every package and version installed. When you issue a composer install in a directory with a composer.lock file, composer will install the exact same packages and versions. Therefore, by pulling a git repo on a production server will replicate the exact same packages in production that were installed in development. Of course the corollary of this is that you never want to commit your vendor/ directory. Since you can recreate it exactly, there is no need to store all of that code in your repo.

It is recommended that also commit your composer.json. When you check out your repo into production and do an install, composer will use the composer.lock instead of the composer.json when present. This means that your production environment is setup exactly like your development environment.
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!
6748 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!

SPONSORS