PHP & Web Development Blogs

Search Results For: service
Showing 6 to 10 of 14 blog articles.
12813 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!
6750 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!
19218 views · 5 years ago
Generate PDF from HTML in Laravel 5.7

Today, I will share with you how to create a PDF file from HTML blade file in Laravel 5.7. We will be using dompdf package for generating the PDF file.

In the below example, we will install barryvdh/laravel-dompdf using composer package and thereafter we will add new route url with controller. Then we will create a blade file. Then after we have to just run project with serve and we can check the PDF file is for download.

Download Laravel 5.7

Now I am going to explain the step by step from scratch with laravel installation for dompdf. To get started, we need to download fresh Laravel 5.7 application using command, so open our terminal and run the below command in the command prompt:

composer create-project --prefer-dist laravel/laravel blog


Install laravel-dompdf Package

Now we will install barryvdh/laravel-dompdf composer package by using the following composer command in ourLlaravel 5.7 application.

composer require barryvdh/laravel-dompdf


Then the package is successfully installed in our application, after that open config/app.php file and we need to add alias and service provider.
config/app.php

'providers' => [
....
Barryvdh\DomPDF\ServiceProvider::class,
],

'aliases' => [
....
'PDF' => Barryvdh\DomPDF\Facade::class,
]


Create Routes

Now we need to create routes for the items listing. so now open our "routes/web.php" file and we need to add following route.
routes/web.php

Route::get('demo-generate-pdf','HomeController@demoGeneratePDF');


Create Controller

Here,we need to create a new controllerHomeController (mostly it will be there, we can skip this step if we don't need to create a controller) that will manage our pdf generation using the generatePDF() method of route.
app/Http/Controllers/HomeController.php

<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use PDF;

class HomeController extends Controller
{
public function demoGeneratePDF()
{
$data = ['title' => 'Welcome to My Blog'];
$pdf = PDF::loadView('myPDF', $data);

return $pdf->download('demo.pdf');
}
}


Create Blade File

In the final step, let us create demoPDF.blade.php in the resources/views/demoPDF.blade.php for structure of pdf file and add the following code:
resources/views/demoPDF.blade.php

<!DOCTYPE html>
<html>
<head>
<title>Hi</title>
</head>
<body>
<h1>Welcome to My BLOG - {{ $title }}</h1>
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod
tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam,
quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo
consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse
cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non
proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</p>
</body>
</html>


Now run the below command for serve and test it:

php artisan serve

6101 views · 5 years ago
Press Release

To say that we have been hard at work here at Nomad PHP, or that I'm excited about these three announcements would be a tremendous understatement. Over the past several months, behind the scenes, we've been working to bring even more features and benefits to Nomad PHP - these have already included unlimited streaming of all past meetings and access to PHP Architect.

Available today, however, you'll also have access to online, live workshops - as well as soon have the ability to stream select PHP conferences live, and finally to prove the knowledge you have gained through our online certification.

Online, Live Workshops

Like our online meetings, we are excited to announce that available today you can participate in online, live, and interactive workshops. Our first workshop will feature Michael Stowe, author of Undisturbed REST: a guide to Designing the Perfect API as he demonstrates how to build the perfect API using modern technologies and techniques.

Additional workshops will be announced as we continue, with a minimum of one workshop per quarter. These workshops will be part of your Nomad PHP subscription, and will be recorded for later viewing.

Nomad PHP Certification

With the many changes impacting the PHP ecosystem, we're proud to announce the ability to prove your knowledge with our online certification. Each certification is made up numerous, randomly selected questions to be completed within a specific time frame. Depending on the exam it may or may not be proctored, but all exams monitor user activity to ensure compliance.

To pass the exam, a passing grade (specified on each exam) must be completed for each section within the allotted time frame. Failure to complete or pass any section will result in a failing grade for the entire exam.

Upon completion, you will receive a digital certification with verification to post on LinkedIn or your website, as well as having your Nomad PHP updated to show the passed certification.

Initial certification exams will include PHP Developer Level I, PHP Engineer Level II, and API Specialist Level I. The PHP Developer exam will cover core components of PHP, the Engineer will cover a broad spectrum of topics including modern technologies, and the API Specialist will cover REST design and architecture practices.

All three exams will be available by January 31, 2019, and will be included with a Nomad PHP subscription.

Stream Select PHP Conferences Live

One of the primary goals of Nomad PHP is to bring the community together, and allow users all over the country to participate in conference level talks. What better way to do this than to bring community conferences online?

Like our traditional talks, these conferences and select conference sessions will be live-streamed as part of your Nomad PHP subscription, allowing you to participate in real-time with in-person conference attendees.

The first conference to be streamed will be DayCamp4Developers: Beyond Performance on January 18, 2018. Additional conferences to be streamed will be announced shortly.

Community and Corporate Sponsorships

With these new additions to Nomad PHP, now is the perfect time to take advantage of our new Community and Corporate sponsorships.

Your support of Nomad PHP not only makes all the above possible, but allows Nomad PHP to continue to serve and give back the community. We're proud, that despite operating at a loss, to have already contributed over$4,000 to the PHP community in the last 5 months.

To learn more about the sponsorship and community opportunities we have available, please visit our Advertising section.

Other Ways to Support Nomad PHP

Of course, while financial support helps us keep afloat and do more for the community, there are even more, and just as important ways to support Nomad PHP. Please consider linking to Nomad PHP, or sharing the service with your friends.
15992 views · 5 years ago
PHP IPC with Daemon Service using Message Queues, Shared Memory and Semaphores

Introduction

In a previous article we learned about Creating a PHP Daemon Service. Now we are going to learn how to use methods to perform IPC - Inter-Process Communication - to communicate with daemon processes.

Message Queues

In the world of UNIX, there is an incredible variety of ways to send a message or a command to a daemon script and vice versa. But first I want to talk only about message queues - "System V IPC Messages Queues".

A long time ago I learned that a queue can be either in the System V IPC implementation, or in the POSIX implementation. I want to comment only about the System V implementation, as I know it better.

Lets get started. At the "normal" operating system level, queues are stored in memory. Queue data structures are available to all system programs. Just as in the file system, it is possible to configure queues access rights and message size. Usually a queue message size is small, less than 8 KB.

This introductory part is over. Lets move on to the practice with same example scripts.queue-send.php
$key = ftok(__FILE__, 'A'); 
$queue = msg_get_queue($key);

msg_send($queue, 1, 'message, type 1');
msg_send($queue, 2, 'message, type 2');
msg_send($queue, 3, 'message, type 3');
msg_send($queue, 1, 'message, type 1');

echo "send 4 messages
";

queue-receive.php
$key = ftok('queue-send.php', 'A');
$queue = msg_get_queue($key);

for ($i = 1; $i <= 3; $i++) {
echo "type: {$i}
";

while ( msg_receive($queue, $i, $msgtype, 4096, $message, false, MSG_IPC_NOWAIT) ) {
echo "type: {$i}, msgtype: {$msgtype}, message: {$message}
";
}
}


Lets run on the first stage of the file queue-send.php, and then queue-receive.php.
u% php queue-send.php
send 4 messages
u% php queue-receive.php
type: 1
type: 1, msgtype: 1, message: s:15:"message, type 1";
type: 1, msgtype: 1, message: s:15:"message, type 1";
type: 2
type: 2, msgtype: 2, message: s:15:"message, type 2";
type: 3
type: 3, msgtype: 3, message: s:15:"message, type 3";


You may notice that the messages have been grouped. The first group gathered 2 messages of the first type, and then the remaining messages.

If we would have indicated to receive messages of type 0, you would get all messages, regardless of the type.
while (msg_receive($queue, $i, $msgtype, 4096, $message, false, MSG_IPC_NOWAIT)) {


Here it is worth noting another feature of the queues: if we do not use the constant MSG_IPC_NOWAIT in the script and run the script queue-receive.php from a terminal, and then run periodically the file queue-send.php, we see how a daemon can effectively use this to wait jobs.queue-receive-wait.php
$key = ftok('queue-send.php', 'A');
$queue = msg_get_queue($key);

while ( msg_receive($queue, 0, $msgtype, 4096, $message) ) {
echo "msgtype: {$msgtype}, message: {$message}
";
}


Actually that is the most interesting information of all I have said. There are also functions to get statistics, disposal and checking for the existence of queues.

Lets now try to write a daemon listening to a queue:queue-daemon.php
$pid = pcntl_fork();
$key = ftok('queue-send.php', 'A');
$queue = msg_get_queue($key);

if ($pid == -1) {
exit;
} elseif ($pid) {
exit;
} else {
while ( msg_receive($queue, 0, $msgtype, 4096, $message) ) {
echo "msgtype: {$msgtype}, message: {$message}
";
}
}

posix_setsid();


Shared Memory

We have learned to work with queues, with which you can send small system messages. But then we may certainly be faced with the task of transmitting large amounts of data. My favorite type of system, System V, has solved the problem of rapid transmission and preservation of large data in memory using a mechanism calledShared Memory.

In short, the data in the Shared Memory lives until the system is rebooted. Since the data is in memory, it works much faster than if it was stored in a database somewhere in a file, or, God forgive me on a network share.

Lets try to write a simple example of data storage.shared-memory-write-base.php
$id = ftok(__FILE__, 'A');


$shmId = shm_attach($id);

$var = 1;

if (shm_has_var($shmId, $var)) {
$data = (array) shm_get_var($shmId, $var);
} else {
$data = array();
}

$data[time()] = file_get_contents(__FILE__);

shm_put_var($shmId, $var, $data);


Run this script several times to save the value in memory. Now lets write a script only to read from the memory.shared-memory-read-base.php
$id = ftok(__DIR__ . '/shared-memory-write-base.php', 'A');
$shmId = shm_attach($id);
$var = 1;

if (shm_has_var($shmId, $var)) {
$data = (array) shm_get_var($shmId, $var);
} else {
$data = array();
}

foreach ($data as $key => $value) {
$path = "/tmp/$key.php";
file_put_contents($path, $value);

echo $path . PHP_EOL;
}


Semaphores

So, in general terms, it should be clear for you by now how to work with shared memory. The only problems left to figure out are about a couple of nuances, such as: "What to do if two processes want to record one block of memory?" Or "How to store binary files of any size?".

To prevent simultaneous accesses we will use semaphores. Semaphores allow us to flag that we want to have exclusive access to some resource, like for instance a shared memory block. While that happens other processes will wait for their turn on semaphore.

In this code it explained clearly:shared-memory-semaphors.php

$id = ftok(__FILE__, 'A');

$semId = sem_get($id);

sem_acquire($semId);

$data = file_get_contents(__DIR__.'/06050396.JPG', FILE_BINARY);

$shmId = shm_attach($id, strlen($data)+4096);
$var = 1;

if (shm_has_var($shmId, $var)) {
$data = shm_get_var($shmId, $var);

$filename = '/tmp/' . time();
file_put_contents($filename, $data, FILE_BINARY);

shm_remove($shmId);
} else {
shm_put_var($shmId, $var, $data);
}

sem_release($semId);


Now you can use the md5sum command line utility to compare two files, the original and the saved file. Or, you can open the file in image editor or whatever prefer to compare the images.

With this we are done with shared memory and semaphores. As your homework I want to ask you to write code that a demon will use semaphores to access shared memory.

Conclusion

Exchanging data between the daemons is very simple. This article described two options for data exchange: message queues and shared memory.

Post a comment here if you have questions or comments about how to exchange data with daemon services in PHP.

SPONSORS

PHP Tutorials and Videos