Author: Levi

Reflection tips for 2018

Reflection tips for 2018

Each new year gives us an opportunity for reflection on the previous. Our accomplishments, failures, and life overall. We often find ourselves making lists of items on which we can improve. How do we determine what is best for us to improve?

I would often find myself making plans to get better at a specific programming language, learn a new one, master design patterns, or a particular algorithm. While I could improve at all of those things is it really what I should spend my time on? I enjoy those things and will do them anyway, so in my opinion, this is a lazy way of planning to get better.

If you’re familiar with the computer science term “reflection,” then you probably understand introspection or self-reflection. Introspection is the examination of one’s thoughts and feelings. This review can help you become a better person, be happier, become more efficient, and many more things.

You can be a brilliant developer, but if you’re an asshole, no one will want to work with you. We should welcome any new ideas with words of encouragement. A crazy idea, in our opinion, could turn out to be a brilliant idea. We should have patience and be less quick to judge or shoot down thoughts. We need to listen to each other carefully. We are rarely put in a life or death situation where a decision has to be made in minutes. Take the time to plan, brainstorm, and think about the problem. Utilize your team if you have one.

Our lives are short, so let’s find ways to enjoy them, and help others enjoy theirs.

Docker Explained for PHP Developers in 2018

Docker Explained for PHP Developers in 2018

This post assumes you have a basic understanding of Docker. But what is a basic knowledge? If you aren’t sure, I suggest you read the Get Started docs, and then you will have a basic understanding of Docker.

I’ve read a few posts on Docker for PHP developers. However, it was the same tutorial on different sites, so I’m not going to copy what they did. I’ll explain the concepts that I struggled with learning.

My objective with Docker is to develop locally and deploy to a Swarm. I hope to have a fast site with high-availability that can be updated and deployed quickly.

Developing Locally

I was recently working on a project that uses SOAP hosted on a slow connection. Instead of hitting that API each page load, I decided to store the results in Redis, and load them from there. This helped speed up the pages that needed to access the data from the remote API. Installing Redis on my local system wasn’t what I wanted to do, so I simply added a Redis service to my “docker-compose.yml” file, and it worked great. You can easily add new services to your stack while developing locally with Docker.

Being able to edit your code, with all the services running, and see the changes immediately is very valuable. I like to develop on Windows, OSX, and Linux, so my environment is drastically different on each machine. It would be very time consuming if I had to have Redis running on each of my dev environments. Having Docker running the same services locally on my dev machines as what is running in production is priceless.

Priceless

The Docker Compose file

You will need two use two “docker-compose” files, one for local development, and one for deploying to your swarm. The main file, “docker-compose.yml,” will be used when deploying to your production environment. And “docker-compose.override.yml” will be used when developing locally. You want to copy your PHP code into the container when you are deploying to production. When you’re developing locally, you want your code outside of the container, so we mount it with volumes in the override file.

Docker Swarm explained in a drawing

You can use Volumes in production, but you will need to copy the files to the node where the container will live. That can be complicated and in my opinion, isn’t ideal. It does work well when developing locally and your computer is the node since the files are already on it.

Docker Services and etc

All of these terms can become confusing, at least they were to me, but I hope to explain them shortly. We used to refer to a “web server” as a server that ran everything a website needed. Even though it was a server running daemons like Apache’s httpd.

Now we have stacks, containers, node, swarms, services, and a lot more words to describe things. Communication is important when speaking with others about the approach you wish to use when solving problems. Understanding what you’re saying is even more important. I’m going to try and define these terms myself.

A service is a piece of software written that we will use to help us accomplish our goals. MySQL, nginx, Apache, PHP, node, and etc are all services we can use with Docker.

Your stack is essentially a list of the services being used for the app. For this example, I’m using haproxy, nginx, and PHP-FPM.

A container is a way to virtualize the service(s) on the computer. FreeBSD has had this ability for a long time with Jails, but Docker has made it much easier. Containers can’t access other resources running on the server.

A node is a single instance of an Operating System. Your computer could be a node, as well as a Virtual Private Server or a Virtual Machine or an entire bare metal server. Node’s run an Operating System that runs the containers.

Swarms are really awesome! They are a collection of nodes and can distribute the containers across them as needed. They can have their own private network and do load balancing.

Swarm

Conclusion

This app is using haproxy, nginx, and PHP-FPM. I’m passing SSL through haproxy so nginx can handle SSL termination because I’m not sure how to do it with haproxy. The load balancer, haproxy, passes the request off to one of the web services. One of the web services, nginx, then connects to a PHP-FPM service to process the PHP.

Be sure to check out the levilol/php-docker repo on Github.

Docker is an excellent tool that I hope to learn more about this year. Other’s have predicted it will get much more attention in 2018 and I agree. I’m going to end this post with my simplified description of Docker.

Imagine if you could compile your app with all the required services and end up with one binary file that contains everything – that is Docker.

Please leave any feedback below in the comments section.

Discover 3 Tips Every Developer Should Know in 2018

Discover 3 Tips Every Developer Should Know in 2018

In this post, I will help you discover 3 tips every developer should know. For the people reading this post who are hoping to learn how to program, no one is perfect, and we all make mistakes, so have fun while you learn. Everyone else, leave a comment below if you can relate or have any other tips!

Debugging

I think it is rare when code works as expected the first time you try it. Sometimes error messages seem very cryptic and are hard to understand, but if you read it carefully, it may give you some context as to what is wrong. Usually, you forgot a semicolon, and you’ll become very familiar with that error message, I am at least.

While you can Google your error messages all day long and find millions of results, they won’t always be helpful, so you need some tools to figure it out on your own. You are expecting your variables to contain specific values, so I usually check to see what is in those variables. Using console.log or var_dump can help you figure out where your code went wrong.

Sometimes you will have to dig a little deeper. So I encourage you to reduce the complexity of the error-prone code until the error goes away. You may want to make a copy of the files current state before you start removing lines of code.

Rick and Morty looking for something

Just remain calm, don’t stress, and use your brain. It may help if you step away from the computer for awhile. Maybe go for a walk or pet your dog.

Trial and Error

If at first, you do not succeed, don’t immediately ask for help, but do try it a different way. Your code may be getting too complicated, and it could be best for you to refactor it. Again, I suggest you step away and pet your dog if you get stuck.

I like to keep a log of what I’ve tried and when I tried it, why I thought it would work, and what happened. Doing this helps me keep track of where I was going with my thoughts. You don’t want to get a hunch and forget it; that’s a waste of your time.

You may need to go back to the planning phase and see if you still think this is the best way to approach the problem. I use pen and paper a lot when I’m working on larger projects. Our minds are incredible, but being organized helps me a lot.

Asking For Help

We all make mistakes. Sometimes, we think the error is not our fault, when in fact it is. Don’t be fearful of asking for help, but also, don’t let it be the first thing you do. Asking for help should be your last resort.

When you do ask for help, give enough information for people to understand the context of your situation, but don’t overload them with garbage. I often find myself typing up a question on StackOverflow when I realize what I did wrong. Even talking out the problem with a co-worker can help you understand what you did wrong. If you don’t have a co-worker, you can always tell your dog. They’re good listeners.

Conclusion

The title, Discover 3 Tips Every Developer Should Know, hopefully, encompasses the content of this post. Should you ever need any help, please feel free to leave a comment, or send me an email.

Advanced PHP is Actually Simple – Learn How Today

Advanced PHP is Actually Simple – Learn How Today

Advanced PHP methods, practices, processes, and everything else can be a bit daunting. If you find it hard to understand some of the documentation or tutorials out there, don’t worry, I can help! I struggled to learn some of the core concepts, but eventually figured it out, I hope I can help you learn with less of a struggle. Having a good development environment is a huge step in the right direction. For work, I use a Windows machine and a MacBook Pro. At home, I have a desktop running FreeBSD. Use whatever you are most familiar.

Packages

You don’t have to do everything yourself; this was a hard lesson for me to learn. There are groups of people who focus on a single PHP package. That package is going to be well written, tested, and hopefully documented. I suggest you use PHP packages when you can. You can browse the available packages on packagist. You will need to have composer installed on your dev machine. If you have an idea for a package, then read my post on creating a PHP package.

Autoloader

The autoloader isn’t magic, but it is very helpful when writing advanced PHP. It will conditionally include the needed PHP files based on the code being run. No longer will you need to have dozens of includes as the autoloader will handle most of them for you. Packages have a registered namespace that tells the autoloader where their files so it can load them. This allows you to easily instantiate a new object without having to include the needed files.

PHP Design Patterns

You’re only making it harder for yourself if you aren’t using design patterns. There are plenty of definitions of design patterns, and none of them make sense. When a definition is defined with other complicated words, I find it confusing. Below is a simple explanation of design patterns.

A design pattern is a way of structuring your code so it can easily be extended, enhanced, or fixed. Most advanced PHP applications will use a couple of design patterns. They’ll help keep your code organized and understandable.

I have written a few posts on different design patterns, such as the adapter pattern, dependency injection, and the factory design pattern. “Design Patterns: Elements of Reusable Object-Oriented Software” by Erich Gamma is an amazing book if you want to learn even more.

Security

There have been a lot of very public data breaches in the last couple months, so I will also cover some basic security tips. Whether your application is used by a couple of people or hundreds, you should always practice safe security. If your app uses a database, an API, or some other type of service, it could be vulnerable.

When you are writing information to your database, please use PDO. PDO is faster and more secure. PDO Tutorial does an excellent job of explaining everything clearly and concisely. Feel free to ask any questions in the comments below.

Another important aspect of application security is protecting against CSRF (Cross-Site Request Forgery). If I were to create an HTML form on my website and set the POST parameter to your website, how would your website know where the post came from? It’s a very difficult thing to do unless you use a CSRF token with your forms. When a user sees a form, you also generate a CSRF token. You add the CSRF token to a session variable and to a hidden input field that is part of the form. Then when the user submits the form, you can check the hidden input field data against the session variable. If they match, then you know they submitted the form from your site.

Visit the OWASP website if you would like to learn more about security.

Advanced PHP Conclusion

Programming is all about solving problems. We take a big problem, break it into smaller problems, solve the smaller ones first, and then we’ve solved the big problem. Keep trying to make your code smaller, simple, and elegant. Programming is art for logical people like yourself. Keep being curious. Let me know in the comments below if you have any questions. I would love to help.

DigitalOcean Spaces – Learn how to use Spaces with PHP

DigitalOcean Spaces – Learn how to use Spaces with PHP

Using DigitalOcean Spaces with your next PHP project is a beautiful idea. Spaces will give you all the hard drive space that you could ever need. This post can help you build your next PHP project with DigitalOcean Spaces. Building out an infrastructure can be a difficult job for anyone, but DigitalOcean’s services make it a bit easier.

Mounting Object Storage

You could upload directly to S3 compatible storage using a PHP package, but it is easier to mount a bucket and let the file system handle the rest. Read my post on Mounting Object Storage if you need help getting started.

By mounting your bucket to your local file system, it will allow you to have nearly unlimited storage space for your app. In addition to storing uploaded files to object storage, you could also save backups, log files, and anything else you could imagine.

PHP Uploading to DigitalOcean Spaces

Your code will probably be a lot more complicated than the example below. However, I think the code below will suffice for this blog post.


<?php
$message = '';
if(!empty($_FILES['uploaded_file'])) {
  $path = 'uploads/';
  $path = $path . uniqid('u', true) . '-' . basename($_FILES['uploaded_file']['name']);

  if(move_uploaded_file($_FILES['uploaded_file']['tmp_name'], $path)) {
    $message = 'The file ' . basename( $_FILES['uploaded_file']['name']) . ' has been uploaded';
  } else {
    $message = 'There was an error uploading the file, please try again!';
    $message .= $_FILES['uploaded_file']['error'];
  }
}
?>
<!DOCTYPE html>
<html>
<head>
  <title>Upload your files</title>
</head>
<body>
  <?php echo $message; ?>
  <form enctype="multipart/form-data" action="upload.php" method="POST">
    <p>Upload your file</p>
    <input type="file" name="uploaded_file"></input><br />
    <input type="submit" value="Upload"></input>
  </form>
</body>
</html>

The code in the example above shows you how to upload a file to a folder. You will need to change the path to where you mounted your bucket. Of course, you will need to make sure you validate the file type and restrict it to users who are logged in.

Conclusion

Digitalocean Spaces is the best object storage service currently available. While they might not have as much space available as AWS, it is compatible with S3, easy to use, and has a better UI.

Please don’t store any sensitive or confidential information in your buckets. If you must, then please make sure you have the proper settings and those files aren’t publicly exposed.


Image Credit DigitalOcean.

Skeleton Repo for PHP, JavaScript, and SCSS

Skeleton Repo for PHP, JavaScript, and SCSS

I work on a lot of different projects, and each one is unique in its own way. I often find myself installing packages manually and then configuring them. It seems like I repeat myself quite a bit, but the requirements of each project vary ever so slightly. In an attempt to prevent myself from repeating the same tasks over and over, I’ve started working on a skeleton repo that contains nearly everything I would need.

What I was doing

Most of my projects are built in PHP and augmented with JavaScript and SCSS. Occasionally I’ll make a project solely with JavaScript. So I would have to run the following commands:

  1. composer init
  2. composer require silex\silex illuminate\database
  3. npm init
  4. yarn add webpack babel-core … and many more

Then I would have to do the following:

  • Configure my composer.json to use PSR-4 autoload for my namespace
  • Create my folder structure
  • Create some interfaces, classes, and models
  • Configure webpack to use my folder structure
  • Import my SCSS

Doing all of this over and over is a waste of time.

Creating a skeleton repo

My decision to create a light skeleton repo has saved me time. Since it is light, it is very easy to scale it back to what I need. However, if I need to add more, I can do so easily. It turns out that I’m quite good at creating a skeleton repo since I’ve done it so many times. By carefully planning and using the steps above, I had one created in about a day. I’ve continued to refine it and add more features.

Conclusion

I’m sure there are some very elegant solutions on there that do what I need, but I enjoy creating these solutions for myself. Perhaps I’ll end up using something someone else created, but I hope that I’ll have a greater understanding of what they’ve done.

New website for a new year

New website for a new year

Keeping a website up-to-date and fresh can be time-consuming, but they need love. I like to give mine an overhaul about once a year, but sometimes I do it twice a year. Today is the day I decided to give my site a refresh.

I’ve had several posts this year, and they’ve ranged from Creating a Game to the Factory Design pattern. The day I run out of things to write about is the day I have learned everything. Needless to say, this day will never come, and there will always be something to write about.

Each year I look back at the things I’ve learned and accomplished. It always amazes me how much I’ve learned and makes me wonder how I ever got this far. Reflection is good for us, and we should all take a moment to inspect our progress.

I need to make a plan for what I hope to learn this year, what I should write about, and repositories I can contribute. Some programming concepts can be difficult for people (including me) to wrap their minds around. I would like to get a better grasp on some ideas so I can write about them on here and help others learn. I’ve noticed several repositories could use some better documentation, so maybe I can help with that. Writing docs isn’t always the most fun task, but you can’t measure the worth of proper documentation.

OWASP

I’m hoping to start the Huntington chapter of OWASP. In my eyes, security has always been critical, but lately, it’s become even more so in the eyes of the many. If I can help our community practice better coding standards, then it is definitely worth my time and energy. We would meet four times a year to discuss best practices for development and ideas we have.

Silex

Silex

This year I’ve continued to try different PHP frameworks. The ones I’ve tried are well written and have a fantastic community. I can see how some people may need to rely on a framework that does everything, but I like having control. And I prefer to add things instead of removing them.

Silex has been enjoyable to use while building web applications. I have a skeleton repo that has everything I need. This repo has webpack for SCSS, JS, and injecting assets into HTML. The folder structure is organized and easy to understand. The organized code is easier to maintain and debug.

Development Environment

Development Environment

Setting up a development environment can be a pain. Sometimes it can be harder than writing the app. Some resources can help you develop faster, but you need to learn how to configure it for what you know, and it’s worth it in the long run.

Gulp is one of those tools that speed up your development, and I’ve been using it for a few months. Gulp is excellent, but Webpack seems to be better and more straightforward to configure. There are still a few other node packages that you will need, such as Babel if you want to write your JavaScript in ES6.

I would like to create a boilerplate for future projects. It would need to contain some automation for PHP, JavaScript, and SCSS. And it would need to be able to test each of those. I’ve started building this boilerplate a couple of times, but I keep starting over. Hopefully, I will finish it soon.

It is worth taking the time to learn about each tool; it’s advantages and disadvantages. Spending a little bit of time planning will save you more time later.

Mounting DigitalOcean Spaces

Mounting DigitalOcean Spaces

I assume you have already created a Space and Droplet on DigitalOcean. If you haven’t, do that now, then come back to this post. In this example I’m using Ubuntu 16.04. I’ve also pointed a domain to this Droplet and put it behind Cloudflare, so Spaces can act as my file repository for my assets, and Cloudflare will deliver them.

Mounting Spaces on your Droplet

  1. SSH into your Droplet and run the following commands:
    • sudo apt-get install automake autotools-dev fuse g++ git libcurl4-gnutls-dev libfuse-dev libssl-dev libxml2-dev make pkg-config
    • git clone https://github.com/s3fs-fuse/s3fs-fuse.git
    • cd s3fs-fuse
    • ./autogen.sh
    • ./configure
    • make
    • sudo make install
  2. Next you need to create a file with your Spaces API Key and Secret Key
    • echo 'KEY:SECRET_KEY' > ~/.passwd-s3fs
    • chmod 600 ~/.passwd-s3fs
  3. Create a mountpoint for Spaces by running mkdir /spaces
  4. Then you need to append the following to your /etc/fstab file
    s3fs#BUCKET_NAME /spaces fuse allow_other,_netdev,nosuid,nodev,url=https://nyc3.digitaloceanspaces.com 0 0
    Be sure to replace BUCKET_NAME with your actual Spaces name
  5. After saving that file, run sudo mount -a .

Now you have unlimited storage capabilities on that Droplet. You could also install nginx and point the root directory to your Spaces mount point. Doing that would allow you to host as many assets as you want, without worrying about space. Maybe you can create the next Imgur.