Month: February 2017

MySQL Relational Database

MySQL Relational Database

If my advice on how to date a model didn’t work, then maybe this will, but probably not. Anyway, you probably wouldn’t want to date a database, it will have other relations at the same time. So instead, let’s learn about relational databases.

There are over 80 million WordPress websites currently on the internet. Each WordPress site uses a relational database. This doesn’t include the other millions of websites that run a different content management system or use a custom solution. Most software uses some sort of database, whether directly or indirectly, it usually has to keep/retrieve data from somewhere.

A database is made up of one or more table. Each table is comprised of fields/columns that can hold different types of data. Each row is usually associated with a PK (PRIMARY KEY). PK’s are unique and auto increment with each new row. While you can have several columns in each table, you need to be careful, and make sure you normalize your data.

Example Table

Below is an example table that could hold employee information. This example will be used throughout this post. I kept it relatively little and hopefully it isn’t complicated.

Table 1.0 (Employees)

ID (PK) name phone company
1 Levi 555-1234 Bulldog Creatives
2 John 555-1235 Bulldog Creatives
3 Alex 555-1236 Bulldog Creatives
4 Jake 555-1237 Bulldog Creatives

Do you see anything wrong with the table above? Is there a way you could make it better or save space? What if we needed to fix the typo and change the name of the company from “Bulldog Creatives” to “Bulldog Creative”?

Normalization

The normalization of data helps you keep your information consistent. Since we are human, we are prone to make mistakes. This technique helps reduce the potential risk of making a simple mistake and save you time.

Reference table 1.0, let’s see how we could normalize the data. The company “Bulldog Creative” is repeated four times and if I listed all the employees, it would be a lot more than that. Let’s create another table for companies.

Table 1.1 (Companies)

ID (PK) company_name
1 Bulldog Creative
2 Rose Bud Flowers

We can now alter table 1.0 to incorporate the “Companies” table as shown below.

Table 1.2 (Employees)

ID (PK) name phone company
1 Levi 555-1234 1
2 John 555-1235 1
3 Alex 555-1236 1
4 Jake 555-1237 1
5 Kristal 555-LOVE 2

Now that we have two tables and they relate to each other, we are headed in the right direction. By normalizing our tables, we are reducing data redundancy and improving data integrity. The column “company” FK (Foreign Key) points to the PK of the “Employees” table.

Conclusion

Using this method will help you in the long run. It may even save your butt. With MySQL, you can put restrictions on UPDATE’s with FK’s, which might prevent you from deleting data that is used somewhere else in your database. If you have any questions, feel free to leave a comment below or send me an email.

PHP Adapter Design Pattern – Learn How It Can Help You

PHP Adapter Design Pattern – Learn How It Can Help You

When I think of an adapter, I think of the three prong to two prong electrical outlet thing. It allows me to plug in an electrical device that has three prongs (one with a ground) into a two prong outlet that doesn’t have a ground. The interface of the outlet is two holes and the interface of the device it has three prongs, so we need an adapter to help us. The PHP adapter pattern utilizes this very concept.

PHP Adapter Example

I’m going to keep going with the electrical outlet idea. Hopefully, this makes a little bit of sense.


<?php

interface ProngInterface {
	public function __construct();
}

interface TwoProngInterface {
	public function __construct(ProngInterface $prongOne, ProngInterface $prongTwo);
	public function plugTwoIn();
}

interface ThreeProngInterface {
	public function __construct(ProngInterface $prongOne, ProngInterface $prongTwo, ProngInterface $prongThree);
}

class Prong implements ProngInterface {
	public $prong;
	public function __construct() {
		$this->prong = '|'; // that is a prong
	}
}

class TwoProng implements TwoProngInterface {
	public $prongOne;
	public $prongTwo;
	public function __construct(ProngInterface $prongOne, ProngInterface $prongTwo) {
		$this->prongOne = $prongOne;
		$this->prongTwo = $prongTwo;
	}

	public function plugTwoIn() {
		echo 'both plugged in.' . "n";
	}
}

class ElectricalOutlet {
	public function __construct(TwoProngInterface $twoProng) {
		echo $twoProng->prongOne->prong . ' ' . $twoProng->prongTwo->prong . "n";
		$twoProng->plugTwoIn();
	}
}

// Our TV *should* have a ground.
class Television implements ThreeProngInterface {
	public $prongOne;
	public $prongTwo;
	public $prongThree;
	public function __construct(ProngInterface $prongOne, ProngInterface $prongTwo, ProngInterface $prongThree) {
		$this->prongOne = $prongOne;
		$this->prongTwo = $prongTwo;
		$this->prongThree = $prongThree;
	}
}

// Here is where the magic happens.
class TwoProngAdapter {
	public $twoProng;
	public function __construct(ThreeProngInterface $threeProng) {
		$this->twoProng = new TwoProng($threeProng->prongOne, $threeProng->prongTwo);
	}
	public function get() {
		return $this->twoProng;
	}
}

$tv = new Television(new Prong, new Prong, new Prong);
// we use the TwoProngAdapter to shave off one of the TV's prongs.
$adapter = (new TwoProngAdapter($tv))->get();
// It'll now work in our two prong electrical outlet!
$outlet = new ElectricalOutlet($adapter);

// we can also plug our two prong toaster into the two prong outlet!
$toaster = new TwoProng(new Prong, new Prong);
$outlet = new ElectricalOutlet($toaster);

Explanation

If you’ve read my other posts, I hope you understand some of the above code. If you’re lost, at least read Classes in PHP and PHP Type Hinting, those should help a little bit.

In the example, the ElectricalOutlet only accepts a device that implements the TwoProngInterface. We really want to watch TV, but it implements the ThreeProngInterface, and we can’t plug it directly into the EletricalOutlet, poop. Now your mom is yelling at you, she really wants to watch Wheel of Fortune, but the TV still has no power.

Luckily, we developed an adapter! The TwoProngAdapter accepts a device that implements the ThreeProngInterface and then returns a TwoProngInterface object. We can now plug in our TV and watch Wheel of Fortune! Congrats! You saved the day and your mother still loves you.

Advice

Read through the code above and see if you can follow the logic in your head. It might help if you read it from top to bottom then bottom to top. If you’re still struggling with it, try typing it up yourself and maybe modify it a little. Learning takes time and you shouldn’t get upset if you don’t understand it right away. It sometimes takes me days, weeks, and sometimes months to understand a concept. Always take a break.

Conclusion

Feel free to comment below. Please comment below. Or email me? Someone has to need some help. If you do ask for help, please share with me all your code and not a sliver of it. I need to see everything that is happening. Sometimes your problem is outside the scope you are focused on.

For those of you who know me, the Wheel of Fortune story never happened, it was made up. I was always prepared.

Disclaimer

Don’t try plugging anything with three prongs into a two prong outlet. I don’t care if you do have an adapter, it is a bad idea. The third prong is for the ground, which can help protect your device from being ruined.

Relationship Models for PHP and MySQL

Relationship Models for PHP and MySQL

Want to be in a relationship with a model? If that has always been a dream of yours, then I might be able to help. I firmly believe if you read this blog post, you’ll be able to attract any person you desire. Intelligence is an aphrodisiac.

This post is really about how I developed my own model capable of handling relationships in a database. That said, it is probably going to get more technical and longer than my other posts.

I wanted to create my own model instead of using a pre-existing solution because I needed a very simple solution. You may use the argument, “don’t reinvent the wheel,” and I will usually agree with you, but not this time. My simple solution did get a little more complicated when I wanted to add another feature. I kept adding features until it could do nearly any type of query that I may find myself using. Reinventing is a method of teaching myself new concepts that I may not normally have discovered.

How I Started

I first created an abstract class that all other models would extend. I chose an abstract class so I could write the logic in the methods and so no one should be able to instantiate it. A model only needs to extend the abstract class to be able to do any CRUD query.

Looking up synonyms for “model” on Google, I found the word “Illustrative” and thought it sounded cool. The name of my base model is called Illustrative. Next, I created a Person class that extends Illustrative. I then started adding some simple methods to the Illustrative class and using them on the Person class. A basic query is a “SELECT” statement so I started with that. I had my database credentials hardcoded in my Illustrative class and created a method to retrieve all the rows from the table. Instead of hardcoding the table name, I decided to make it the plural form of the class name, so “SELECT * FROM persons” was the query that was getting run.

At this point, I hadn’t done anything that excited me so I had to keep going.

Static Methods

When using a static method, you don’t need to instantiate the class, which is the way I like to do it. It really comes down to preference, as do most things, so do what you like.

A newly instantiated class is returned when you call one of the static methods that the model inherits from Illustrative. This gets things started and allows you to use method chaining to build your entire query. Below are two examples of how it can be used for instantiating and method chaining.


$result = Person::fetch()->order('id', 'desc')->get();
$result = Person::fetch()->order('id', 'desc')->limit(1)->get();

As long as I thoroughly document all the methods and their parameters, this will help someone who isn’t familiar with SQL retrieve rows from the database. I think it is verbose enough to English vernacular to make it seem familiar.

Saving Records

While your program should probably read from the database more than it writes, it still needs to be able to create new rows. Assuming the Baller class extends the Illustrative class, you could do something like below.


$p = new Baller;
$p->name = 'alex';
$p->save();

This allows you to dynamically assign new properties to the class and then run the save method to add the new row. Some people aren’t a fan of dynamically adding properties, so I made another way to do it. The other way is shown below.


Baller::insert(['name' => 'levi']);

In case you are wondering, yes, Alex and I are ballers.

Finding Certain Rows

At first, I retrieved all the rows from the database and filtered the results based on the parameters. I knew this wasn’t a good way to do it, but I did it anyway. I later went back and corrected it. It now uses SQL to limit the results from the database.


$rows = User::fetch()->where(['name', '=', 'levi'])->get();

The example above is using the User model and running the static method fetch. By that, I hope you can deduce we are fetching a user. Instead of getting all of the users, we specify the where the method and pass an array to it. In that example, we are looking in the name field that is equal to “levi.”

While most of your queries may be simple, sometimes you have normalized your database and need to get information from multiple tables. I was a bit hesitant to move onto defining relationships, but I did, and I believe that is what makes this package useful.

Relationships

Writing a query that includes a JOIN isn’t very difficult, but writing a method in PHP to accomplish this was a little challenging. I’ve used frameworks that can handle this, but I’ve never tried to figure out how they do it. I dug into some code written by others and I turned up with nothing.

I eventually got the logic worked out, but my query results weren’t matching what I expected. I was getting a little frustrated, so I decided to sleep on it and let my diffused mode thinking take over. I woke up the next day with a fresh outlook on the project and found my mistake. I also redid some of the logic of the other methods.


$r = Post::fetch()->users()->where(['name', '=', 'levi'])->get();
var_dump($r);

Conclusion

I am not claiming to be intelligent. My opening paragraphs are usually my attempt at humor, and as poorly done as they may be, I don’t think I’m going to stop.

You can’t force yourself to see what is wrong. Take a break. Go for a walk, take a nap, talk to a friend, or do something other than work on that project. You could also switch to another project. Doing these things allows your brain to go into the diffused mode and work on the problem. Even though you aren’t actively thinking about it, your brain is looking at the problem from a wider perspective. That doesn’t mean your brain stopped.

I still need to add an update method, but you can check out the Illustrative repo.

Interface or Abstract Class

Interface or Abstract Class

I was recently working on a project, and I found myself adding the @property DocBlock to an interface. I knew it wasn’t good practice, but the class that is implementing that interface will provide those properties. I tried to convince myself it was okay.

Interface

Yes, it is a good idea to have your concrete classes implement an interface. It helps you plan how the class should work. Another benefit is using the interface as a type hint, you can then pass your concrete class as the parameter. This also allows someone to create their own implementation of the interface and pass it as a parameter.

An interface is essentially a signature. It can’t really do anything except provide a skeleton of what the class has to implement. You can’t declare properties, you can’t write any logic, and it can’t cook you breakfast. Although it can’t do much, you’ll usually use an interface instead of an abstract class.

Since an interface can’t define properties, what I was doing, was wrong. There was no agreement between the interface and the concrete class that said it must implement those properties. It is undefined behavior and would cause headaches down the road.

Example


<?php

interface CreateDropletRequestContract {
	public function __construct($name, $region, $size, $image);
}

class CreateDropletRequest implements CreateDropletRequestContract {
	// . . .
	private $name;
	private $region;
	private $size;
	private $image;

	public function __construct($name, $region, $size, $image) {
		$this->name = $name;
		$this->region = $region;
		$this->size = $size;
		$this->image = $image;
	}
	// . . .
}

Abstract Class

An abstract class can not be instantiated. With an abstract class, you don’t implement it, you extend it. Since the abstract class can provide logic, you must extend it to keep the logic. When you implement something, that means you are going to write the logic for it. Abstract classes can also define properties, which was I needed to do for my project.

A concrete class can only extend one class, but it can implement many interfaces. So when you are thinking everything out, try to plan ahead, even if it’s hard or you end up being wrong. The more you plan, the better you’ll get at doing it, and the easier it will become.

Example


<?php

abstract class CreateDropletRequestContract {
	private $name;
	private $region;
	private $size;
	private $image;

	public function __construct($name, $region, $size, $image) {
		$this->name = $name;
		$this->region = $region;
		$this->size = $size;
		$this->image = $image;
	}
}

class CreateDropletRequest extends CreateDropletRequestContract {
	// . . .
	// Most of the code could already be written in the abstract class.
	// . . .
}

Conclusion

I might ditch the abstract class and only implement the concrete class since it is only a data transfer object without an interface. Feel free to send me an email if you have any questions.

Example


<?php

class CreateDropletRequest extends RequestContract {
	// . . .
	private $name;
	private $region;
	private $size;
	private $image;

	public function __construct($name, $region, $size, $image) {
		$this->name = $name;
		$this->region = $region;
		$this->size = $size;
		$this->image = $image;
	}
	// . . .
}
Securing a Server

Securing a Server

This post will cover securing a Linux server. Back in the day, I started with Red Hat 6 and Slackware 4; I still have a book from when I was learning Red Hat 6. I also ended up learning FreeBSD, but I’ll save that story for another post.

I’m not claiming to be an expert in server security, but if you follow these tips, it’ll be a good start in the right direction. I don’t recommend you learning these things on a production server, because I have locked myself out several times, probably more than I can count. You try these out on a test server; you can create a new DigitalOcean droplet for free if you don’t already have an account.

SSH keys

Ideally, your server is on a speedy network, and the specs are decent. However, this also may help people brute force your passwords. An alternative to using a password is to use an SSH key, they are even more secure that passwords.

An SSH key is much harder, if not nearly impossible, to crack. Quantum computing may change how all encryption and security works, but we don’t need to worry about that right now. Your SSH key can be protected with a passphrase, it will help prevent anyone being able to use your key, or you can have one without a passphrase. It’s a personal preference you may decide which way to do it. They would actually need your private key (file) even to attempt to use it, so don’t give out your private key.

If you want to get access to a server, you can send someone your public key without worrying about any consequences. Before, you would have to call someone or email them your password which can be risky.

Here is a good tutorial on how to setup SSH keys.

ed25519

Some people prefer to use ed25519 keys since they are smaller and faster. These are designed to work with ECDH (Elliptic Curve Diffie-Hellman) key agreement scheme.

I am not a fan of the ECC (Elliptic Curve Cryptography), even though I use it every day. If I recall correctly, a few companies and the NSA all claim they own the patent rights for ECC. I don’t trust something that is faster and smaller that is supposedly more secure. I’ve done quite a bit of research on this, and I understand how it can be smaller and quicker. I don’t have any evidence that it isn’t secure, it’s just speculation.

Change your SSH port

Changing the port SSH listens on can help tremendously. There are lots of botnets that run port scans on the internet every day. They look for standard open ports, like port 22, which is what SSH uses. If they scan your server and see you have that port open, they will then try to brute force your server. If they don’t know what port you’re listening on, then they generally move on.

DigitalOcean has an excellent tutorial on changing your SSH port.

fail2ban

If they don’t move on and they continue to hammer your server, you should create a firewall rule that blocks them. It’s probably impossible to monitor your server(s) 24 hours a day, so I highly suggest you use fail2ban to do it for you. You can configure it to block an IP address after X amount of attempts and for how long. It is highly customizable and one of my favorite things to keep an eye on. When I check my fail2ban stats and see the number of bans, it makes me happy.

This works along with the firewall iptables. Here is a helpful tutorial on getting fail2ban setup on CentOS.

Conclusion

You should employ these suggestions, and I encourage you to research these things on your own. Come to your own conclusions on what is best for you and your infrastructure.

If you decide the methods above are helpful, then that is awesome, but you may require more. You might need to be PCI or HIPAA compliant, and that’ll take more work, so keep researching these topics.

If you’re interested in learning more about ECC, check out this overview of cryptography by Gary Kessler.

Disclaimer

These are suggestions and not fool-proof methods to protect your server. These are some of the things I do when I’m setting up a new server.

Perceptual Hashing

Perceptual Hashing

Disclaimer: This is not a post about how you can get high and see things in a new light. Or is it?

You may assume that computers know everything and they don’t need people to do anything. We have assistants on our phones that we can talk to and ask questions, so who cares about how things actually work. Well, I do care, and I think this is pretty nifty.

I was recently tasked with writing a program to find duplicate images. I thought, no big deal, I’ll use a cryptographic hash and find the duplicates that way. And that way would work, but what about images that are similar to each other? Unfortunately using a cryptographic hash, like MD5 or SHA512, wouldn’t help you. The cryptographic hash algorithms use a waterfall effect to make the result completely different when only a few bits are changed in the source file.

After a little bit of research, I decided to use perceptual hashing.

What is Perceptual Hashing?

A perceptual hash is made up of a sample of the data from the original file. If you were to examine two pictures like you would read a book (from the top down and left to right), stopping every inch and recording the color; you would be creating a perceptual hash for that image. To keep it short, let’s say you end up with:

  • Blue
  • Blue
  • Blue
  • Yellow
  • Green
  • Green

Then if we examined another picture that is similar to the first, we might get:

  • Blue
  • Blue
  • Blue
  • Yellow
  • Orange
  • Green

As an intelligent human person, you can obviously tell they are similar. Now you can also use a systematic way to tell they’re similar since you can say there is only one color different. Of course, actual pictures are made up of a lot more pixels and colors.

Hamming Distance

Just how similar are they? Are they close? Are they the same? How would you measure the similarity? Well, you can use the Hamming distance. You would first XOR the two perceptual hashes; then you would count the number of ones in that binary string. That will give you the Hamming distance. Some people may say the Levenshtein distance would work better, but I’ll disagree. I’m not going to put an example of finding the Hamming distance on here because I don’t want to get too technical in this post.

Conclusion

These explanations may not be 100% accurate, but it is how I decided to explain them. I feel as if they accurately represent the underlying foundation of the concepts. If you would like to see how to measure the Hamming distance, send me an email, and I’ll send you some code I wrote along with an explanation. I’m okay if you want to create a new email address and pretend to be someone else ;).

I went ahead and wrote a function in C that finds the Hamming distance and I put it in a Github Gist. I’m not sure it is working correctly, so don’t use it for anything in production. I have PHP version that is working if you would like to see it.