I write code. I also lift heavy things, bike, and try to stay in weird poses. I speak Spanish fluently and one day my Japanese will be fluent too. Casual eSports fan and cat owner.
Don't wanna be here? Send us removal request.
Text
PHP Phun #2: Array Methods
PHP Phun #2: Arrays (And Wonked Up Array Methods)
The Topic: Every Array is Associative
People (rightly and justifiably) love to give PHP grief for its native array methods. There’s a ton of inconsistencies on function arguments and function return values that feel unintuitive.
Even apart from array functions themselves, there’s a lot of confusion about arrays in general. The one thing you must remember, above all, is that all arrays in php are hash tables.
ALL arrays are key-value maps. They are all associative arrays. Even if you’re just shoving values into an array without specifying keys, it’s still an associative array; php has just decided to be nice enough to give you keys that happen to be consecutive integers starting from zero.
Even though I know that all php arrays are associative arrays, some odd and unexpected consequences of this still get me.
The Problem: The Return of Array Filter
I was investigating the cause of a bug when I nailed it down to the return value of an array_filter call. A rough approximation of the code was something like this:
$filteredElement = array_filter(function ($element) {....}, $array)[0];
Now with this filter, I was 100% certain that the function would always return exactly one value, but for some reason there were times where $filteredElement was null. If I knew I was always getting a value back, why was it empty?
Well, because the return of array_filter is an associative array and it preserves the original naming of the keys.
Let’s say the array I passed in was this one:
[‘zelda’, ‘link’, ‘gannon’]
Under the hood, that’s secretly:
[ ‘0’ => ‘zelda’, ‘1’ => ‘link’, ‘2’ => ‘gannon’].
If my array_filter returned back the ‘gannon’ element, the array I’d be getting back would actually be:
[ ‘2’ => ‘gannon’].
This is not what’d you’d expect, as a lot of other languages would give you back
[ ‘0’ => ‘gannon’ ].
Because I was getting back [ ‘2’ => ‘gannon’], I wasn’t getting anything when I tried to access the element with zero as my key, [0].
One thing you can do to prevent this is wrap the array_filter in array_values. This will take all the values from the array and put them in a new array with numeric, sequential indexed keys.
0 notes
Text
PHP Phun #1 : Namespacing
As someone who is primarily a JS developer, one of my goals is to get more into back end and application architecture. Thankfully, this is something my job encourages and during the last few months I’ve gotten to write quite a bit of PHP for our apps. I’ve been productive, but since I never invested the time to actually learn PHP basics, and because PHP has quite a few quirks, I’ve come across many tiny things that became time sucks for me.
Over the last few weeks I’ve been putting in the time to nail down those PHP basics. I decided to start writing about them as a way of helping myself remember.
PHP Phun is a series about all those minor bugs that got me. The kind of bugs a PHP newbie makes. It’s also about neat things I’ve learned and don’t want to forget. First, I’ll talk a bit about the general topic and then I’ll talk about the specific thing I struggled with.
Now, for the first installment in PHP Phun:
The Topic: Namespacing!
By default, all function and class names are defined on the global namespace. The consequence of this is that if you define a Cat class in one file, you can use it in another (assuming that the file is being required in somehow).
However, another consequence is that you can have collision between function and class names. If you imported in another file, maybe from an external library, that file might contain as Cat class as well. How can you specify which Cat class you want to use?
You differentiate between the two using namespaces. You simply define your Cat class to be in a specific namespace and then in the file in which you’re actually using it, you use the ‘use’ keyword to declare the namespace you want.
CatClass.php
<?php
Namespace mycat;
Class Cat {
// whatever you cat does
}
Index.php
<?php
Use mycat;
$cat = new Cat(); // this will be the kind of cat you’ve defined
The problem: The difference between use \App\Cats vs use App\Cats.
This is one of those subtle differences that’s easy to ignore when you’re just trying to quickly make things happen. At first I actually thought there was no difference and that the difference between use \App\Cats and use App\Cats was stylistic. I was wrong.
When you have a backslash before your namespace, you’re designating that you want to start looking for that namespace starting from the global namespace. Without the initial blackslash, you’re designating that you want to start looking from whatever the current namespace is.
Namespace App/Cat;
Use Meow; // this resolves to the namespace App/Cat/Meow
Vs.
Namespace App/Cat;
Use \Meow; // this resolves to the namespace Meow
Now, hopefully, you don’t end up like me and can avoid spending 30 minutes trying to figure out why your program can’t seem to resolve your class name.
0 notes
Text
Cross Origin Resource Sharing and JSONP
While working on a coding challenge I was tasked with creating a front end page for an API end point. The specific API I was told to use returned JSONP. I had never heard of JSONP at this point but I figured it couldn’t be much different from regular old JSON - honestly the name doesn’t make it sound like it is - so I started playing with the end point, making regular AJAX requests to it.
I quickly realized that my method wasn’t going to work. After a bit of research I discovered what JSONP actually was, and how to use it.
Put simply, JSONP is JSON response wrapped in a function. The way it works that is that you make a API request, detailing the name of the function you want to wrap the JSON in and the API will do the wrapping.
Lets say you have a function called bark(), you want to get something back from the API wrapped in the bark() function, so you would make an API call that looks something like:
coolestdogs.com/api/randomDog?cb=bark
The API will then return to you some JavaScript that looks like this:
bark(coolestDogJSON) {
// whatever you decided to do with coolestDogJSON
}
Now why is this useful? Can’t the API just return to you some JSON and you can call the function on your own?
This is useful because it’s clever hack to get around issues with Cross Origin Resource Sharing (CORS). CORS is a spec that stops your browser from making certain requests to a domain different from the one the current page is served on. This can sometimes make it annoying to deal with making AJAX requests, especially when you know you’re requesting a safe resource.
So how does JSONP relate to CORS? It turns out, that one way of getting around CORS is just make a <script> tag and set the source to be the API endpoint, instead of making an AJAX request. This will ignore any cross domain issues. JSONP wants you to do just that. And by naming the callback function, you have the ability to actually use the JSON response.
0 notes
Text
Let’s talk about MVC
When I first started programming in JS, it felt like every article I read would mention MVC, Model-View-Controller. It would always come up somehow, in blogs, in class, in conversation. But it was the kind of thing that no one ever took the time out to explain (and I didn’t take the time out to look up) so I took the term for granted. It was just kind of something I associated with frameworks. Angular? Backbone? Yea, of course those are all MVC frameworks.
Since then, I’ve done my fair share of research and my students have done their fair share of asking about MVC. So I’ve decided to write a guide to MVC - What is it? Why do you need it? What the advantages and disadvantages?
So really, what is MVC?
MVC is a design pattern. It’s a way of organizing the structure of applications that have user interfaces. An MVC framework will give you objects / classes that will help you organize your code into the following categories:
View: The View is simply everything your user can see, the UI, the output of your application.
Model: This is the actual data and content backing your application.
Controller: The controller goes between your model and your view and defines what happens when the user interacts with your UI.
Why do I need it?
Let’s talk about your latest cool application, PuppyJam. It’s a website that lists instruments for dogs. You have a database full of instrument information and the HTML/CSS of your UI views. But how do you connect them? Should each page of PuppyJam have it’s own JS file that fetches the appropriate information from the database? What if you have some JS that could be used across multiple pages? If you have similar views, should you just copy and paste the same HTML over and over?
Using an MVC framework will help organize your code into objects that fit the MVC categories and help control the flow of data.
Why is this awesome? I’m not totally convinced…
The best part about an MVC framework is that is decouples your View and the Controller logic. They become two separate, modular objects, such that they don’t need to know about each other. This makes it easier to make changes to either and easier to debug.
This separation also makes your code more reusable. Perhaps you have two Views that require the same logic in the background. Well, now you can reuse your Controller for those two Views!
Sounds great! So why do non MVC frameworks exist?
Sometimes our greatest strength is also our greatest fault - the worst part about an MVC framework is that is decouples your View and Controller logic.
As an application grows, you’ll start creating more Views, likely nesting views, and you’ll probably start to see Views that require similar Controllers. Let’s say you have two Views and the two Views require similar, but not identical Controller logic. Well, instead of writing two Controllers that are similar, you might just write the logic of both controllers onto the same one, such that each View is backed by more logic than it needs. Or you might write three Controllers, one for the shared logic and two for the independent logic, creating more than one Controller per View.
Now you have a soup of views and controllers and it takes you a frustratingly long amount of time to figure out which Controller knows what if you need to debug something.
So what do I do?
Whether or not an MVC framework is the answer to your spaghetti code questions depends on what your application is. Your application may start with an MVC framework and then outgrow it, or perhaps it might start as a simple jQuery backed page and grow into one. Like most libraries and frameworks in programming, there is no blanket answer, just the right tool for the right job.
0 notes
Text
Debugging in React
As part of my job I have to help new students get through workshops. These workshops are generally fullstack applications that utilize a variety of different JavaScript tools - some of which I have little experience using on my own. Most recently, the workshops were themed around learning React, a front end JavaScript library for creating modular, easy to maintain user interfaces. Debugging others' work in React provided a challenge, especially because React bugs tend to be small errors rather than major errors with conceptual understanding. In order to help others debug better, I decided to walk my students through these four principles.
Know your debugging tools
The React Developer Tools are a life saver. This Chrome extension will allow you to inspect your components on the page, easily seeing their props and subcomponents. If you're using Redux, redux-logger is a must. Being able to read a log of dispatched actions and store changes will make debugging the Redux portion of application infinitely more simple.
Know your typos
I've noticed that almost universally, people will make the same small typos over and over again. Try to remember the small errors you'll make instead of just glossing over them. There's few things more frustrating than staring at your code for twenty minutes only to realize you typed React.componet instead of React.Component.
Know your ES6
I'll admit that before using React, I ignored ES6's class syntax. If I had read up on class syntax before diving into React, I would have saved myself a lot of trouble debugging. I recommend reading MDN's documentation on classes. Knowing your arrow functions won't hurt either.
Know your docs
I'm not the type of programmer who reads documentation first. I usually dive into code examples, start coding, and then use documentation to supplement as I go along. I do not recommend taking this approach with React. The documentation for React is amazingly well written. It's very much meant to be read and meant to be followed. Reading the quick start guide for React will set you up for understanding how React is organized and how to approach breaking down your ideas.
0 notes
Text
Click Handlers and Event Bubbling
While working on a React application, I came across a problem where I had inconsistent behavior behavior when I clicked on on a button. It was this button actually:
In the handleClick method I needed the button’s value attribute. However, sometimes it was undefined and sometimes it was exactly what I expected. For a long while I couldn’t figure out why this happening. I probably clicked this button about a hundred times before I noticed that a slight change in where I clicked caused different values for the value attribute. That’s what made me realize what was going on. My handleClick method looks roughly like this:
Here, I was expecting that event.target would always give me back the element that the handler was attached to. I fell into the trap of forgetting about how events bubble up the dom.
When you click on a DOM element, the onClick event traverses up the DOM looking for any registered listeners on that element and all its parent elements. Because of this, if an element with a click handler has child elements, the click handler will be run when its children are clicked as well as when the element itself is clicked.
In my example, if I clicked on the button element, the click handler on the click was triggered. If I clicked on the span element, that also triggered the clicked handler on button.
Now, how is this related to my inconsistent value in handleClick? The answer is that clicking on different elements gave my event property a different target. An event’s target is the element that originated the event, so I could only get the value property off my target when I clicked on the button and not the span. My solution for this was to change event.target to event.currentTarget. An event’s currentTarget is the element that the click handler is attached to - in my case the button, which is exactly what I wanted.
This bug was a reminder that no matter how well versed I am with frameworks like Angular, there’s no excuse to get lazy with my vanilla JavaScript fundamentals. I’m glad that I decided to learn React for this project because it’ll allow me to refresh my basics.
0 notes
Text
Lodash’s _ .clone vs _. cloneDeep and References in JS
The lodash documentation on _.clone contains this little gem:
var objects = [{ 'a': 1 }, { 'b': 2 }]; var shallow = _.clone(objects); console.log(shallow[0] === objects[0]); // => true
In JavaScript, comparing two objects with the same properties and values returns false, so how is it that shallow[0] and objects[0] are equal?
The answer is that shallow[0] and objects[0] are actually the same object.
Everything in JavaScript is a reference. If you don’t know what a reference is, think of it as an address. The same way that a home or business address tells you where to find something, an address to your computer tells it where it can find a piece of memory - in this case your variable values.
So our objects[0] is an address. It’s an address that tells your computer where it can find the value { 'a': 1 }. When you use _.clone it makes a copy of the address and gives it to shallow[0]. objects[0] and shallow[0] point to the same object and then evaluate to true when compared.
If this is still unclear, pretend that shallow is a UPS worker and objects is a FedEx worker. They both have the address to your house, and the value of your house is { 'a': 1 }. For shallow, they store your address in shallow[0]. Similarly, objects is storing your address at objects[0]. They are just two different names for the same address. They both have a copy of your address, so they can both find your home and drop off a package.
Now shallow comes to your home and drops off package ‘b’ with value 2 at your home.
shallow[0].b = 2
Now the value of your house is { 'a': 1 , 'b': 2 }. A few hours later,objects drops off package 'c’ with value 3 at your home.
objects[0].c = 3
The value of your home is now { 'a': 1 , 'b': 2 , 'c': 3 }.
The takeaway here is that _.clone will return a new object to you with new copies of references to the same objects. If you think of your first object as an address book, the cloned object is a just a copy of the same address book. When you compare two variables that have been 'copied’ with _.clone, you’re really comparing the same object.
If you want make a copy of an object that is its own variable in memory, you have to use _.cloneDeep. This would be like making an entire new copy of the house instead of making a new copy of the address. You can see an example of this in the documentation for _.cloneDeep.
Note: This blog post first appeared in a a blog I co-author, Verey Projects. You can view that blog post here.
0 notes