PHP – SitePointhttps://www.sitepoint.com
Learn CSS | HTML5 | JavaScript | Wordpress | Tutorials-Web Development | Reference | Books and MoreFri, 09 Dec 2016 19:00:14 +0000en-UShourly1https://wordpress.org/?v=4.4.2What’s New and Exciting in PHP 7.1?https://www.sitepoint.com/whats-new-and-exciting-in-php-7-1/
https://www.sitepoint.com/whats-new-and-exciting-in-php-7-1/#commentsThu, 08 Dec 2016 17:00:12 +0000https://www.sitepoint.com/?p=145201The PHP community has gone viral with the latest PHP 7 announcement and all the goodies it brings to the language. The PHP 7.1 release has more good news and features to offer. This article highlights the most important ones, and you should check PHP RFC for the full list.

ArgumentCountError Exception

Earlier versions of PHP allowed for function calls with fewer arguments than specified, emitting a warning when you have a missing argument.

Nullable Types

PHP 7 added type declarations for parameters and return types, but it seemed that something was missing! Nullable types enable for the specified type to take either that type or null. Here's an example:

]]>https://www.sitepoint.com/whats-new-and-exciting-in-php-7-1/feed/4The Delicious Evils of PHPhttps://www.sitepoint.com/the-delicious-evils-of-php/
https://www.sitepoint.com/the-delicious-evils-of-php/#commentsMon, 05 Dec 2016 17:00:42 +0000https://www.sitepoint.com/?p=144926I want to look at two PHP functions: eval and exec. They're so often thrown under the sensible-developers-never-use-these bus that I sometimes wonder how many awesome applications we miss out on.

Like every other function in the standard library, these have their uses. They can be abused. Their danger lies in the amount of flexibility and power they offer even the most novice of developers.

Let me show you some of the ways I've seen these used, and then we can talk about safety precautions and moderation.

Dynamic Class Creation

The first time I ever saw dynamic class creation was in the bowels of CodeIgniter. At the time, CodeIgniter was using it to create ORM classes. eval is still used to rewrite short open tags for systems that don't have the feature enabled...

More recently, though, my friend Adam Wathan tweeted about using it to dynamically create Laravel facades. Take a look at what the classes usually look like:

These facade classes aren't facades in the traditional sense, but they do act as static references to objects stored in Laravel's service locator class. They project an easy way to refer to objects defined and configured elsewhere, and have benefits over traditional static (or singleton) classes. One of these benefits is in testing:

That's a neat trick. Whether of not you use (or even like) Laravel facades, I'm guessing you can see the benefits of writing less code. Sure, this probably adds to the execution time of each request, but we'd have to profile performance to decide if it even matters much.

]]>https://www.sitepoint.com/the-delicious-evils-of-php/feed/7Using GDELT 2 with PHP to Analyze the World!https://www.sitepoint.com/using-gdelt-2-with-php-to-analyze-the-world/
https://www.sitepoint.com/using-gdelt-2-with-php-to-analyze-the-world/#respondFri, 02 Dec 2016 17:00:11 +0000https://www.sitepoint.com/?p=144651Are you interested in political world events? Do you want to play with one of the world's largest databases? If you answered either of those questions with a yes, keep reading - this will interest you!

I will show you a simple example of how to use GDELT through BigQuery with PHP, and how to visualize the results on a web page. Along the way, I will tell you some more about GDELT.

GDELT

GDelt (the "Global Database of Events, Language and Tone") is the biggest Open Data database of political events in the world. It was developed by Kalev Leetaru (personal website), based on the work of Philip A. Schrodt and others in 2011. The data is available for download via zip files and, since 2014, is query-able via Google's BigQuery web interface and through its API, and with the GDELT Analysis Service.
The GDELT Project:

monitors the world's broadcast, print, and web news from nearly every corner of every country in over 100 languages and identifies the people, locations, organizations, counts, themes, sources, emotions, quotes, images and events driving our global society every second of every day, creating a free open platform for computing on the entire world.

Online Experimenting

All GDELT data has been made available through BigQuery. This "big data" database has a web interface that allows you to view the table structures, preview the data, and make queries while making use of the autosuggest feature.

In order to experiment with the GDELT dataset online, you need to have a Google account. Go to the BigQuery dashboard.

If you don't have a Google Cloud project yet, you will be prompted to create one. This is required. This project will be your working environment, so you may as well choose a proper name for it.

You can create your own queries via "Compose query". This one, for example:

]]>https://www.sitepoint.com/using-gdelt-2-with-php-to-analyze-the-world/feed/0Sending PHP Event Messages to Remote Logstash on Windowshttps://www.sitepoint.com/sending-php-event-messages-to-remote-logstash-on-windows/
https://www.sitepoint.com/sending-php-event-messages-to-remote-logstash-on-windows/#respondWed, 30 Nov 2016 17:00:53 +0000https://www.sitepoint.com/?p=144573By opening this article you've endeavored yourself to expanding your knowledge of PHP applications as part of event-baseddistributed systems. You'll be given a quick intro into what we are referring to when we say event messages, what Logstash is, and why it is so cool.

If you've already heard of Beats or understand you can run Logstash locally to ship logs to another Logstash instance or directly to a datastore such as Elasticsearch, this article is still for you and will show you an easy-to-configure-and-run, hopefully more effective and certainly fun-to-use alternative.

Quick Intro into Event Messages and Logstash

With event messages, we gather information about events that occur in our applications, be it business-oriented decisions of the applications' users, decisions made by the applications themselves, or their failures. Each event, besides the message it conveys, is typically determined by a timestamp and a type such as informational, warning or error. A record of an event is an event log.

Additionally, there's also Event Sourcing - a somewhat different but also somewhat similar concept which you may want to check out.

There are many tools built specifically for the purpose of shipping logs to datastores for later analysis and making knowledge-based decisions. Logstash is one of them, and because of the vast number of input, output, codec and filter plugins it offers, the most popular. Out of the box, it can read from Heroku app logs, GitHub webhooks or Twitter Streaming API, create new events and send them to Graylog, IRC, or JIRA.

The event messages would ordinarily be of interest to the users of your applications, too. In an application, one page would generate events and another one would display them in an aggregated form.

Let's consider an example where the first page publishes new blog posts and the other one lists all blog posts related to PHP that have been published in the last month. The application could have talked to a relational database directly for both read and write. But with event messages it is decoupled from the database so other subscribers can be added easily, e.g. an email list or a more performant datastore like Elasticsearch.

Publishing Events

For quick comparison, let's first consider event publishing on Linux with Rsyslog, the favorite syslog of many computer systems.

Since both Rsyslog and Logstash use RELP, a TCP based protocol for reliable delivery of event messages, sending that message to Logstash requires adding only two short statements to the Rsyslog configuration file.

]]>https://www.sitepoint.com/sending-php-event-messages-to-remote-logstash-on-windows/feed/0Event Sourcing in a Pinchhttps://www.sitepoint.com/event-sourcing-in-a-pinch/
https://www.sitepoint.com/event-sourcing-in-a-pinch/#commentsMon, 28 Nov 2016 17:00:06 +0000https://www.sitepoint.com/?p=144381Let's talk about Event Sourcing. Perhaps you've heard of it, but haven't found the time to attend a conference talk or read one of the older, larger books which describe it. It's one of those topics I wish I'd known about sooner, and today I'm going to describe it to you in a way that I understand it.

Most of this code can be found on Github. I've tested it using PHP 7.1.

I've chosen this title for a few reasons. Firstly, I don't consider myself an expert on the topic. For that, you'd be hard pressed to find a better tutor than the authors of those books, or someone like Mathias Verraes. What I'm about to tell you is only the tip of the iceberg. A pinch of salt, if you will.

Event sourcing is also part of a larger, broader set of topics; loosely defined as Domain Driven Design. Event sourcing is one design pattern amongst many, and you'd do well to learn about the other patterns associated with DDD. In fact, it's often not a good idea to pluck just Event Sourcing out of the DDD toolbox, without understanding the benefits of the other patterns.

Still, I think it's a fascinating and fun exercise, and few people cover it well. It's especially suited for those developers who have yet to dip their toes in the pool of DDD. So, if you find yourself needing something like Event Sourcing, but don't know or understand the rest of DDD, I hope this post helps you. In a pinch.

Common Language

One of the strongest themes of Domain Driven Design is the need for a common language. When your client decides they need a new application, they are thinking about how it will affect their ice-cream sales. They're concerned about how their patrons will find their favorite flavor of ice-cream, and how that will affect foot-traffic at their ice-cream stand.

You may think in terms of website users and geolocated outlets, but those words don't necessarily mean anything to your client. Though it may take some time, initially, your communication with your client will be greatly improved if you both use the same words when talking about the same thing.

You'll also find that modeling the entire system in the words your client understands gives you a bit of a safety net against scope changes. It's much easier to say; "You initially asked for customers to purchase ice-cream before the invoice is sent (shown here in code and email), but now you're asking for the invoice to be sent first..." than it is to describe the changes they're asking for in language/code only you understand.

That's not to say all your code needs to be understood by the client, or that you have to use something like Behat for your integration testing. But, at the very least, you should call entities and actions the same thing as your client does.

An added benefit of this is that future developers will be able to understand the intent of the code (and how it applies to the business process), without as much help from the client or project manager.

I'm waffling a bit, but this point will be important when we start to write code.

]]>https://www.sitepoint.com/event-sourcing-in-a-pinch/feed/4How to Properly Deploy Web Apps via SFTP with Githttps://www.sitepoint.com/how-to-properly-deploy-web-apps-via-sftp-with-git/
https://www.sitepoint.com/how-to-properly-deploy-web-apps-via-sftp-with-git/#commentsSat, 26 Nov 2016 17:00:15 +0000https://www.sitepoint.com/?p=144259Uploading files is an integral aspect of any deployment process, and the underlying implementation can vary depending on the type of your server.

You can easily upload your files to an SFTP server using an open source desktop client like Filezilla. Those who have used this are aware that this process is cumbersome and irritating as it doesn't let us automate our deployment process, and we always need to upload the whole project, even if we have modified only a part of the files of our codebase.

The PHPSECLIB (PHPSecure Communications Library) package has an awesome API for routine SFTP tasks: it uses some optional PHP extensions if they're available, and falls back on an internal PHP implementation otherwise. You don't need any additional PHP extension to use this package, the default extensions that are packaged with PHP will do. In this article, we will first cover various features of PHPSECLIB - SFTP, including but not limited to uploading or deleting files. Then, we will take a look at how we can use Git in combination with this library to automate our SFTP deployment process.

Installation

composer require phpseclib/phpseclib

This will install the most recent stable version of the library via Composer.

Authentication

By default, password authentication is used to connect to your SFTP server. A cryptographic key-pair is more secure because a private key takes the place of a password, which is generally much more difficult to brute-force. Using phpseclib, you can connect to your SFTP server with any of the following authentication methods:

RSA key

Password Protected RSA key

Username and Password (Not recommended)

RSA Key

We will assume that you have a secure RSA key already generated. If you are not familiar with generating a secure RSA key pair, you can go through this article. For a video explanation, you can refer to Creating and Using SSH Keys from Servers For Hackers.

Uploading and Deleting Files

A large part of the deployment process includes uploading files to a server. Uploading files essentially means transferring the contents of a local file to a remote file. The example below creates an index.php file on the server with the contents This is a dummy file:

]]>https://www.sitepoint.com/how-to-properly-deploy-web-apps-via-sftp-with-git/feed/14What Would You Pay to Make 27% of the Web More Secure?https://www.sitepoint.com/what-would-you-pay-to-make-27-of-the-web-more-secure/
https://www.sitepoint.com/what-would-you-pay-to-make-27-of-the-web-more-secure/#commentsFri, 25 Nov 2016 17:00:29 +0000https://www.sitepoint.com/?p=144197It’s Open Source Week at SitePoint! All week we’re publishing articles focused on everything Open Source, Free Software and Community, so keep checking the OSW tag for the latest updates. Scott Arciszewski, known on Twitter as CiPHPerCoder, is to security what Chris Hartjes is to unit testing. He’ll pounce on insecure applications, libraries, and packages, […]

]]>https://www.sitepoint.com/what-would-you-pay-to-make-27-of-the-web-more-secure/feed/2Pay the Price for Open Sourcehttps://www.sitepoint.com/pay-the-price-for-open-source/
https://www.sitepoint.com/pay-the-price-for-open-source/#commentsWed, 23 Nov 2016 17:00:37 +0000https://www.sitepoint.com/?p=144023Gather 'round kiddies, Uncle Cal has a history lesson to share.

Back when the world was young

Back in the early days of Open Source - when Dinosaurs roamed the earth and Rasmus was a young man - there were two types of open source projects we talked about: those that didn't cost any money, and those that gave you the freedom to redistribute and modify the code. The analogy we used was that projects were "Free as in beer" if they didn't cost anything, and "Free as in libre" if they gave you the freedom to share with others. That was how we explained Open Source to muggles back then, and there were muggles everywhere. It should be noted that this was also back in the time when the first step in learning PHP was compiling the Linux kernel on your server.

Modern Day

Fast forward a few dozen years and here we are, Open Source is now an ecosystem, not a user group that you and five friends attend, or a magazine to which you subscribe. The problem is that most of us have stopped talking about the different types of open source, we just assume it is both. Most of the projects in our corner of the world - PHP - actually is both. The PHP license - a derivative of the BSD license - is very open about giving you freedom with very few responsibilities. Other projects use GPL, MIT, Apache, and other licenses. Each developer or group has the right to select whatever license they feel most comfortable with for their code. If you use their code, it is your responsibility to abide by the restrictions and responsibilities of their license.

Most developers who use open source understand everything I said in that last paragraph. We get it. If it's GPL, we have to ship the code, if it's MIT, we have to leave the copyright and name on it, etc. Most of us understand the basic ramifications of licenses, even if we haven't delved into the dark details. But using Open Source code carries with it another responsibility, another price if you will.

My friend Elizabeth Smith said it best in her talk at ZendCon '17: "If you use Open Source, but you don't contribute to Open Source, Open Source will die."

That is the price of Open Source: giving back. It is the price that some developers and most companies that make their living or profits off of Open Source forget to pay. Giving back is not a tip that you are giving back to Open Source, giving back is an implied responsibility.

How to Give

"Ok, Uncle Cal, we get it, whom do we pay?"

See, if you are thinking that, then you really don't get it.

Yes, almost any of the PHP Core Developers would love to have you slip them a couple hundred for their time. If enough of us did this, some of them could dedicate all of their work hours to making PHP even better. But that's not how we give back. Money can be earned. When I say giving back, I mean giving the one thing that can't be earned and once given, cannot be replaced. When I say you need to be giving back to Open Source, I mean giving your time. For companies, that means giving each developer on your staff time to give back to the Open Source project of their choice (their choice, not yours). For individuals, this means getting involved in your favorite project. For some of us that is writing code, for others, it's documentation. For some like me, it means writing tutorials, giving talks at user groups and conferences, and doing whatever we can to educate; to help build the next generation of developers.

This week is Open Source Week at SitePoint.com. While we do usually cover open source here, what with all the tutorials and introductions to amazing new libraries, packages, and frameworks, this week will be a little "theoretical" for a change.

We'll discuss open source in general, think about how it's affecting our programming language's landscape, what we can do to help it spread, cover some interesting open source projects, and more. Be sure to check out other channels - we're spreading Open Source Week across the entire site with this tag, and across Twitter with the #OpenSourceWeek hashtag.

For now, let's look at some open source projects in dire need of contributors and Github stars.

GPGMailer is a package that lets you send GPG-encrypted emails (using zend-mail and Crypt_GPG).

Email security is often an afterthought or, well, not a thought at all - so seeing a package that focuses on making sending secure emails a priority is a breath of fresh air. GPGMailer can come in handy if you're building your own email client, or if you're doing something hacky like filtering recruiter spam from your inboxes and auto-replying to them.

At 33 stars, the project could use some love - both in being tested, and in solving the one tricky issue of a freezing Travis pipeline. Check it out!

]]>https://www.sitepoint.com/sourcehunt-open-source-week-edition/feed/1Quick Tip: The Convenient Magic of Eloquent Observershttps://www.sitepoint.com/quick-tip-the-convenient-magic-of-eloquent-observers/
https://www.sitepoint.com/quick-tip-the-convenient-magic-of-eloquent-observers/#commentsWed, 16 Nov 2016 17:00:08 +0000https://www.sitepoint.com/?p=143498If you've used Eloquent on medium to large projects before, you may have encountered a situation where you want to take action when something happens to your models. Eloquent provides a convenient way to do so.

The Observer Pattern

The observer pattern is a software design pattern in which an object, called the subject, maintains a list of its dependents, called observers, and notifies them automatically of any state changes, usually by calling one of their methods. - Wikipedia

In our case, Eloquent models can notify us about changes on a given model.