A quick tip for working with Print Styles

If you have to do a lot of work with print styles it can get super annoying because the only way to preview your changes is to hit “command + p” in the browser and have it open the print pdf preview. It’s slow and cumbersome to do it that way and there is a much better solution.

Open the developer tools in Chrome or Brave, then go to options -> more tools -> rendering -> emulate css media type “Print”. Here is a screenshot showing the setting:

After this you can inspect anything you want and see how it’ll look when printed right in the normal browser window.

In your code editor, dock your sidebar to the right

A few months ago I moved the sidebar in my code editor to the right and I love it. In fact, I’m sad I’ve been writing code for 20 years without ever doing this before. If you’ve never tried it, you should and here is a video by Jeff Sagal demonstrating why it’s useful:

I have all of my editors, that allow it, set up this way and I don’t think I’ll ever go back to a left sidebar again. Look at how beautiful VS Code is, and no janky code moving when you open it.

vscode.jpeg

Framework Defaults

Sebastian Schlein on why you should stick to the default Laravel architecture:

Projects which are built by teams of developers and that take months to build, need to be easily maintainable. They should be easy to understand and follow as much default conventions as possible. Why? Teams change.

How do you prepare a project for changing teams? Stick to the most common standards and use boring technologies. So if you use Laravel, do not introduce an additional architecture on top of it. It takes more time to build this architecture, and every time a new developer joins the team, you need to teach your way of doing things. It takes time until they become productive, and if a deadline is near, you miss the opportunity of outsourcing a feature to a freelancer to get everything done in time. The custom architecture requires time to learn, and this is exactly the resource you don’t have at this moment. Goal failed.

I am of the same mind as Sebastian.  When I started with PHP, no frameworks existed, and as soon as I tried one, I was immediately hooked because of the advantage that any developer anywhere in the world, with knowledge of the framework, could jump in on day one and know what is going on. As soon as you start changing the defaults it adds even more overhead to the whole codebase.

It’s like going to your regular grocery store. It’s comfortable, you know where things are and can be in and out without much fuss. Then compare that with being on vacation where you have to visit a new grocery store. You can’t find anything, what typically takes ten minutes now takes thirty, and it’s super frustrating.

Sticking to the defaults also pays dividends on projects that are not long-lived. I have apps that are many years old that still work and only require the occasional bug fix. Because I stuck to the defaults I can quickly jump in, make the fix, and go on with my day. In apps where I’ve changed them, it feels like it takes half the day to relearn how it works and why it works.

I prefer simplicity, and the defaults are simple.

Deploy on Friday?

There are two trains of thought on the question of should you deploy on a Friday. One believes you should deploy on Friday’s because if you have a sound system in place, you can always roll back, the other thinks it is not worth the risk.

Both of these people are correct, and if you have a complete automated deployment process complete with rollbacks, and the rollbacks are continuously tested, then sure go for it.  But in every other case, I don’t think the risk is worth it.

If it’s an emergency sure, but I’ve rarely found a deploy to be so important, it’s worth disappointing my wife and kids if it goes wrong. The risk/reward is just not close to being worth it for me. Work can wait.

 

Be kind in code reviews

From the Nerdery’s documentation on code review guidance:

Be kind. Yes, a person is not their code, but writing code is a creative act. Creators are by nature intimately involved with their creation. You’re going to be critiquing another person’s creation, at a minimum, be kind when you do it. Better yet, find positive as well as negative things to say. We want both the code and the coder to be better once you’re done; don’t make it easy to reject your constructive observations by being a jerk about it.

Lot’s of other great advice in the linked document, but this one really resonated with me.

If Else in SQL

Today I hit an interesting problem and when creating a report for an internal billing system. The system itself automatically bills each customer every year and we have two types of customers. One that pays with a credit card through Stripe, and another type that we invoice and their billing departments pay.

Because invoices take longer for us to be paid we always create the invoice 30 days before it’s actually due and for Stripe customers,​ we do it 7 days early. This way if anything goes wrong like a declined credit card it gives them extra time to fix it before becoming delinquent.

Of course, the side effect to this is it causes our stored “next billing date” to be 7 or 30 days off depending on the type of customer, and we keep the original date in case the customer ever decides to switch from one to the other.

With that setup out of the way, I needed to create a list of customers ordered by when they would be billed. Like all things, there are many ways to solve this but for this, I decided to do it directly through SQL. What I wanted to happen was if an organization is a Stripe customer then creating a “real_bill_date” set to 7 days before it’s due, otherwise create a “real_bill_date” to 30 days prior.

Here is the query I was able to create:


SELECT
  CASE
    WHEN
      organizations.stripe_active = \'1\'
        THEN
          DATE_SUB(next_bill_date,INTERVAL 7 DAY)
    ELSE
      DATE_SUB(next_bill_date,INTERVAL 30 DAY)
  END AS real_bill_date,
  organizations.*
FROM
  organizations 
WHERE 
  subscription_active = 1
ORDER BY 
  real_bill_date ASC

This uses SQL WHEN/ELSE clauses to determine what should be happening. Basically translating into “if Stripe is active, then subtract 7 days”, “else subtract 30 days”.

This is useful for the next time you think you have to do a query and then do a query looping each to get a calculated field. Yes, that typically works but is process intensive and can lead to timeouts. Doing it directly through SQL is usually much faster.

PHP: Underscores for Private

Jeffrey Way released a new Laracasts Snippet, and in it, he mentioned a tweet from me:

In the podcast, he talked about how PHP felt more “libertarian” in the early days. The underscore represented that this should be protected or private and even though this is a recommendation from the creator of the code, you are an adult, and if you want to do something with it, then you accept the risk.

The language and community have since switched the stance, and now everyone wants to restrict it with the feeling that if it’s code you are writing, then you know best how it should be used.

I’m not sure one way is better than the other, but as I mentioned in the tweet, I miss the old days.

Find Your Top 10 Shell Commands

Ever wonder what shell commands you use most often? Copy and paste the following into your CLI and see your top 10.

history | awk '{print $2}' | sort |uniq -c | sort -rn | head -10

Here is a list of mine from my dev machine:

  • 574 git
  • 461 cd
  • 422 vim
  • 314 ls
  • 202 gss
  • 109 exit
  • 97 php
  • 68 sudo
  • 64 ag
  • 41 ..

I think it’s fun to see what you use most often. Also, as a bonus, if you are a PhpStorm user go to help -> productivity guide to see what features of the IDE you use most often.

Building Laracon Online

This will be the third year we’ve been running Laracon Online and I have learned a lot about selling tickets in the process. Based on this tweet I was reminded of how we’ve reworked the order system over these three years and I wanted to share with you the progression.

The first year we used a third party service to sell tickets. For the percentage they would take we assumed it would be a decent deal for us since we wouldn’t have to build out any of the infrastructure. However, I was swamped with support that year. I had hundreds of people entering their email addresses wrong and other weird stuff. It was a nightmare.

From this point we decided we would build our own system for the next year and I tried my best to build the simplest system possible. You hit the /pay route, added all the emails you wanted to buy tickets for, entered your account info, and pay. Behind the scenes we would email all the people and tell them to reset their password to create an account. It was simple and worked great.

Now that we had all this data for this year I was brainstorming on how I could make it even easier for people to purchase and I came up with the idea of just pre-filling the checkout system with all the people you purchased tickets for last year. So if you work at a company buying tickets for 20 people all you have to do is confirm they all are the same and hit buy.

Thinking through all this took some time but the implementation was really straightforward and only took me a night of hacking.

As developers we want to focus on the code and think about how to design apps that are easy for us, but our focus should always be on the end user. Even if it adds complexity or makes our app harder to manage later. The customer is the priority and making their life easy is why we are here.

Everything is always a trade off, just make sure you are prioritizing what is important.

Set your Terminal to Red for Production

Making mistakes in production is one thing that always scares me. This problem multiplies if you use a lot of terminal tabs but a quick and easy solution is to make production red so it’s immediately noticeable where you are logged into.

For the image above I’m using Termius on iOS which supports this and allows you to set it on a folder level and then any ssh connections under the group inherits the color.

It’s a really simple way to help distinguish which connection you are logged into and can be a life saver. This can done in other terminals too, just do a web search to find instructions for your app of choice.

Refactoring For Prose

I’ve worked with a lot of legacy applications and one thing that I have seen many times is small things that are confusing. For example, I recently came across some code that looked like this:

if ($foo) {


    $noAction = true;


} else {


    $noAction = false;


}

That is pretty straightforward and easy to grasp. But what comes next is where the problem lies:

if (! $noAction) {


    //...


}

If we read this as a sentence it says, “if not no action” and most of us struggle figuring out what the double negative translates too. It’s not something that we encounter very often in English so when we see it our brains turn to mush.

From my experience things like this are common in older procedural code because you are defining the variable so far away from the use that it either morphed into the current style over time, or the variable is used in several different contexts and this was the path of least resistance when it was originally coded.

While you are coding try to think through things like you are writing prose. In this example, maybe something as simple as renaming the variable to $doAction would be sufficient.

if ($foo) {


    $doAction = false;


} else {


    $doAction = true;


}




if($doAction) {


    //... 


}

In my opinion reading “if do action” is much clearer and easy to grasp.

Sleep on it

The old saying, “sleep on it”, meaning spend some time tonight thinking about the question and have an answer tomorrow.  It’s a common phrase in our language but how often do you literally put aside time to actually think about it?

Having a busy life outside of work with family, hobbies, dinner, everything else it’s really hard to set aside time to just sit and think. I’ve had to start using the time just before bed, mornings, or go for a walk alone.

Yesterday I was working on a new integration an app we recently launched and I had to work on adding a new API endpoint. It was all really straightforward.  However, last night as I was reviewing my day before bed I started thinking about the way I solved the problem and realized I may have made a mistake because I forgot about a constraint from the service that’s going to be reading it.  While trying to solve that in my head I realized I solved the entire problem wrong and I should redo my work.

What I do each night is review my day like I was a star in a TV show and I’m following myself around as the cameraman with the goal of looking at my decisions from a different standpoint. This is what helps me attempt to remove my biases, but of course, that doesn’t always work. It is pretty good at allowing me to see mistakes though, and that’s why I do it.

I know many programmers spend their after work hours coding and being on the computer but I implore you to take a break. Get away from the screen and you’ll actually do better work.

 

Striving for Simplicity

I recently launched Laravel Events and it was one of those projects that came to life because I wanted to better keep the community informed on what all local events were happening.

As I sat down and started planning the project I wanted to start with the goal of doing the absolute minimum to make it work. This is just a small side project, no money involved, just a directory, so it doesn’t have to be complicated.

At the core that would be a form to submit the event information, a way for me to edit/approve/delete it. That way it would account for spam, invalid listings, etc.

To do this I had to make a tradeoff, and that was once you submitted a listing you can’t edit it. In fact, I don’t know even know who submits. I’m storing zero data on you, and only the public event information.

I’m sure you are thinking, “but what about when they need to change something related to an event?”, and that has come up but since launch, it has only happened twice. It also only took me about 20 seconds to make the change for them so, in my opinion, it’s been a good tradeoff. Once it starts being a greater burden then I will rethink that part and editing.

When I see developers starting new side projects they almost always overcomplicate it. Keep things simple, until they are a problem, and then revisit. It saves a lot of time and headache in the beginning.

Process Cards with Stripe + Twilio

Stripe just announced support for Twilio Pay:

Phone payments are especially common in industries like food, travel, healthcare, retail, and nonprofits, but payment details are often keyed in manually by a human agent. This flow can be riddled with errors and expose companies to security and compliance risks. That’s why we’re partnering with Twilio to help companies integrate phone payments quickly while ensuring the checkout flow remains secure and PCI compliant.

With Twilio <Pay>, businesses can now securely collect payment details with an interactive voice response flow, which is useful for automating payment experiences such as bill collection or donations. For a more personalized experience, employees can also walk customers through an order over the phone: when it’s time to collect the payment, the agent activates Twilio <Pay> to let the customer enter payment info using their keypad—agents can follow the customer’s progress, but won’t see or hear the card details.

This will be huge for anyone that handles phone sales or customers that struggle with online forms. It reminded of an interaction I recently had with a live chat agent where I wanted to switch a subscription to a new plan. For whatever reason, they said that they would need to cancel my current order and then have me resubscribe and re-enter my payment info. They were able to push a new popup to me that included all the forms and outside the agent’s eyes. I thought it was clever.

What Makes PHP Popular?

I saw this question pop up on a forum and I know every PHP developer has their own reasons, it made me think of why I initially picked PHP way back in the early 2000’s when v4.3 was king.

It all started when my family hired a web developer to create a website for their motorcycle dealership. Everyone was moving to the web, and we didn’t want to be left behind. We ended up hiring a local guy, and a few months later a new website was delivered that was built entirely with Microsoft Front-page. He sat with me for an hour or so and showed me the basics on how to update it, took his check, and then went on his merry way.

Flash forward about two months, and I was spending half my day on Front-page forums trying to figure out the tool and how to make cool things. I loved it! Eventually, though I was sick and tired of Front-page, the extensions kept breaking, and every time it was a nightmare to fix.

This led me to a crossroads. I wanted to remake the site so it was dynamic and so we could quickly add new inventory. The two languages I heard was best for this was either ASP or PHP. To a newbie, they both seemed like greek, but PHP hosting was cheaper, so that is the direction I went.

With the language chosen, I started reading everything I could and tinkering, but it didn’t “click” I struggled more than I’d like admin with understanding the relationship between PHP, MySQL, and Apache. Keep in mind back then I had zero tech friends and nobody local I could even ask. It was trial and error from tutorials and forums.

What I ended up realizing is the part I struggled with was that I couldn’t actually see the relationship between all these tools. Around this time I tried Dreamweaver, and it helped tremendously because it was all basically integrated into a single app.

As I compare then to today the training material now is leaps and bounds better than we what we had. Yes, web development is way more complicated today, but everything from tutorials, to training videos, to even open source apps. Everything is better explained than back then.

So to finally answer the question, “What makes PHP popular?”, For me, it was cheaper hosting, and once I grasped the basics, I never left the community. If it works, embrace it.

IDEA – IKEA Style Instructions for algorithms

IDEA a unique project that uses IKEA style of instructions to explain algorithm assembly instructions. From their about page:

IDEA is a series of nonverbal algorithm assembly instructions by Sándor P. Fekete, Sebastian Morr, and Sebastian Stiller. They were originally created for Sándor’s algorithms and datastructures lecture at TU Braunschweig, but we hope they will be useful in all sorts of context. We publish them here so that they can be used by teachers, students, and curious people alike.

All IDEA assembly instructions are licensed under a Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International license, or CC by-nc-sa 4.0 for short.

Simple PHP Refactoring

Today I needed to write some code to grab a list of CC addresses from an email, and I thought showing the steps I took could make for an entertaining blog post.

I know everyone works differently and when I’m facing a coding challenge the first thing I do is try my best to just get it to work. I don’t care how the code looks or anything. The only goal is to make it work. Here is my first working attempt at solving the problem of grabbing the CC’s:

/**
 *
 * Returns an ​array of email addresses
 * ['john@example.com', 'jane@example.org'];
 *
 */
public function getCC() 
{
    if ($ccs = $this->getHeaderByKey('cc')) {
        $adrListArray = imap_rfc822_parse_adrlist($ccs, null);
        $ccs = [];
        foreach ($adrListArray as $item) {
            $ccs[] = $item->mailbox.'@'.$item->host;
        }
        return $ccs;
    }
    return false;
}

This code is using PHP’s imap_* functions to first see if the CC header is set in the .eml file, then the imap_rfc822_parse_adrlist function to parse an email address string. This is useful to normalize​ the output of an email address list. The getHeaderByKey either returns the string of the header or false.

After I got it working the temporary variable was really annoying me, so I next refactored to the following:

public function getCC() 
{
    if ($ccs = $this->getHeaderByKey('cc')) {
        $adrListArray = imap_rfc822_parse_adrlist($ccs, null);
        return array_map(function($item){
            return $item->mailbox.'@'.$item->host;
        }, $adrListArray);
    }
    return false;
}

That started feeling better, but I really don’t like that all that code nested inside the if.

public function getCC() 
{
    if (! $ccs = $this->getHeaderByKey('cc')) {
        return false;
    }

    $adrListArray = imap_rfc822_parse_adrlist($ccs, null);
    return array_map(function($item){
        return $item->mailbox.'@'.$item->host;
    }, $adrListArray);
}

Now it feels cleaner to me and could be further simplified by removing the $adrListArray temporary variable:

public function getCC() 
{
    if (! $ccs = $this->getHeaderByKey('cc')) {
        return false;
    }

    return array_map(function($item){
        return $item->mailbox.'@'.$item->host;
    }, imap_rfc822_parse_adrlist($ccs, null));
}

Personally, I think it’s cleaner than what I had the start, but even now I’m not 100% happy with it. I don’t like the $ccs variable assignment in the if statement, I think the method name should be changed to better represent this returning an array of email addresses. It’s not a single CC.

I think it’s a fun exercise writing out why you made the improvements that you did and thinking through how to make your code readable. I know this is subjective, but I find the last example easier to grasp vs. ​the first. What do you think? Do you see any other improvements that could be made?

Laravel: Disable Timestamps on Models

A few days back someone sent me a message with an issue on all the old posts on Laravel News. It wasn’t a huge bug but to fix it I had to resync all the posts from the WordPress install and as I was running through them I noticed that all the updated_at dates were then out of sync. Technically they are correct since I updated each post, but I wanted to keep the original date.

Laravel provides the ability to set this on demand and I could just include it in my command and have it ignore updating each timestamp. Here is a quick example:

$post->content = $data->content;
$post->timestamps = false; // Dont change the timestamps on save.
$post->save();

Of course, if you don’t want timestamps at all you can disable it on the Model level through the public $timestamps = false; property.