Skip to content

u/pdizz

In this archive from Aug 2008 to Feb 2023

4
posts
69
comments
0
media
643
score
class User extends Db ...

that will make it very tricky to mock the database adapter. You would be better off assigning the db class to a property of the user class, and injecting it in the constructor or something else (ie dependency injection). that way in your test you can just build a user object with a mock db adapter instead of the real thing. (bonus you could also inject db adapters for other dbs besides mysql in the future

if you ever hear the phrase "composition over inheritance" this is what theyre talking about

edit: nevermind, looks like you are already doing this. no need to extend Db if you are also injecting Db

4 points

So trying to figure out which exceptions throw when, or if I'll get an Exception or a PHP error has been a matter of trial and error.

Can you wrap the whole worker process with try/catch and catch \Throwable (base interface for both \Error and \Exception)?

Rabbitmq has a built in feature for handling failures called a "Dead Letter Exchange" (DLX) which can be applied to a queue or to all queues. When a message times out or is explicitly rejected, rabbitmq will automatically move it to another queue. You can then have a worker on that queue which picks up the failed messages and decides what to do. This worker can re-queue the message to the working queue to have it re-processed, reject it if it can't be processed at all, send notifications, etc

A basic pattern i've used is to have an "attempts" parameter in the message body that is incremented by the main worker. If a message is rejected or fails the DLX worker checks the number of attempts against a limit i've configured, and either sends the message back to the original queue to be processed again or rejects it. This way you can give your worker more chances to finish the message, but wont clog up your queue with messages that are impossible to process.

edit: https://www.rabbitmq.com/dlx.html

edit 2: Correction after looking at my old code, the DLX worker increments the "attempts" parameter before re-queuing the message, which makes sense as the process worker wont be able to alter and re-queue the message depending on what goes wrong. Anyway, the thing you want to avoid is impossible messages that can never succeed sitting in the queue forever and blocking other messages.

3 points

For an intuitive SQL builder that is not an ORM I like Zend\Db\Sql

If you are comfortable with SQL but dont want to mess with chopping up sql strings it makes it very easy to do stuff like build a base selection and add filters:

use Zend\Db\Sql\Select;

class ClientSelect
{
    /**
     * Select clients for an account
     */
    public function selectClients($accountId)
    {
        $select = new Select();
        $select
            ->from('client')
            ->columns([
                'id' => 'client_id',
                'client',
                'user_id' => 'created_by_user_id',
                'created_timestamp',
            ])
            ->join(
                'address', // table
                'client.client_id = address.client_id', // on
                ['address', 'city', 'state'], // columns
                'inner' // type
            )
            ->where(['client.account_id' => $accountId]);

        return $select;
    }

    /**
     * Select a single client record by its id
     * Using the base client selection and adding where clause
     * prevents selecting a client outside of the account
     */
    public function selectClientById($id, $accountId)
    {
        $select = $this->selectClients($accountId)
            ->limit(1)
            ->where(['client.client_id' => $id]);

        return $select;
    }

    /**
     * Select a filtered list of clients
     */
    public function selectList($accountId, array $filters = [])
    {
        $select = $this->selectClients($accountId);
        if (isset($filters['user_id']) && null !== $filters['user_id']) {
            $select->where(['created_by_user_id' => $filters['user_id']]);
        }

        return $select;
    }
}

It uses a similar style for insert, update, delete. Also works well with Zend\Paginator to select ranges

3 points

Once you install it, you'll notice that the php binary isn't in your path

That seems odd since this is done automatically when you install it via webtatic repo. I'd be interested in a bit more detail on why this is the "correct" way to do it

1 points

A framework (or at least a set of standards) comes in really handy if you're working on an api with multiple developers. If you're always arguing about the best way to handle pagination, or what the json response should look like, or solving the same problems over and over in slightly different ways, your backend will become a mess over time. Frameworks can take a lot of the guesswork out of these kinds of common development tasks that are usually separate from your business requirements.

Anyway, this is much less of an issue in smaller or solo projects since it's easier to keep things consistent and make sure everything is using the common core

1 points

This is one of the reasons a lot of frameworks are becoming less monolithic and moving towards being a collection of component libraries. There are a lot of useful components in Symfony and Zendframework that you can leverage in your business code now without having to couple it to the MVC core. I would recommend aiming somewhere in the middle between hitching your wagon to a monolithic framework like ZF1 and rolling your own hydrators, validators, DI, etc

1 points

All unit tests are not created equal. When you're constrained by time, try to focus your test coverage on what will give you the most value for your time spent. It's sometimes easier to say what NOT to test.

Tests that I often see but provide very little value and should be low priority or avoided all together:

  • Testing getters and setters of a class. An easy way to improve your test coverage numbers, but unless they're doing something extra like validation, there's not much value in testing these
  • Testing language features. Testing that a method call will fail if you pass the wrong type for a type-hinted parameter is really just testing PHP at that point
  • Goes with the previous one, but testing functionality of 3rd party libraries. They should have their own tests.
  • Tests that can never fail, or falsifying the results. This is tricky to spot, but sometimes you end up testing artificial results that you create yourself within the test, using mocks or otherwise

What to test:

  • Business logic. Especially if you already have clearly defined requirements, these tests almost write themselves, and are valuable for catching regressions
  • Expected error cases or exceptions. If you expect something to throw an exception under certain circumstances, write a test for those circumstances
  • Known bugs. If you fix a bug, write a test for the expected behavior with the given circumstances, and you will hopefully never see that bug again.
9 points

Check out Expresive which is sort of the preview of ZF3. I liked what they were going for with ZF2's event system, but it was too heavy-handed. Expressive is simply a queue of middleware components that act on the request/response and either continue or error out. IMO it's what ZF2 events should have been, all the power and flexibility without mind-melting complexity.

6 points

All of the tools and practices around PHP are as important as learning the language. Learn how to pull in packages with Composer. Even if you don't have any external dependencies, composer is useful for autoloading your classes. Learn namespaces, psr-0 and psr-4, and set up auto-loading for your classes. This is all stuff that CI doesn't have but is the standard for modern PHP development

1 points

I think maybe you're getting hung up on having to know and understand everything that's going on under the hood in a framework to be able to use it. I tend to be the same way. The thing is, you don't have to know it all to be able to use it right away. If you read the guide and follow the conventions it does work, and can keep building stuff and be productive. The more you build with it the more the framework reveals itself to you. There is a lot of "magic" that goes on with some frameworks that can be very off-putting, but if you dig deep enough it's all just PHP.

In my current role I've been working with Zend Framework 2 for over a year and I understand maybe 80% of what happens from when a request is made to when the response is sent (ZF2 is about as opaque as you can get for PHP frameworks). Despite that I've been able to build dozens of API's in that time. Things like input validation, content negotiation, pagination and other tedious things that never really change but always need to be done are just handled, leaving me to worry about business logic and not much else.

No one can know everything, and if you want to take advantage of these higher level abstractions you have to let go of knowing everything that's happening underneath. I have a very vague understanding about how PHP stores arrays in a hash table, but that doesn't stop me from using them every day. Anyway, there's some things you could do to make your life easier.

  • Like others have said, get Vagrant and get yourself a LAMP VM to get your environment up and running. Scotch Box is a LAMP VM that works for most PHP applications out of the box. No need to spend hours installing PEAR packages
  • Get xdebug working in your IDE. It's fully functional and relatively trivial to set up
  • Get something working and go from there. It's a lot easier to learn how something works when you already have a working example to play with
4 points

I did the same thing migrating an application from zf1 to zf2. Creating a new index.php has many advantages, most of which is being able to leave your current application untouched as you move pieces over. Once you migrate a feature over, you can deprecate the old one for a while to make sure you don't have any regressions before removing it.

1 points

Keyboard shortcuts

Move and act

jork
Next / previous post or comment
Enteroro
Open the post
f
Open the media viewer
s
Save
h
Hide (the toast has Undo)
Tab
Right after an action: the toast's Undo
x
Collapse the comment
v
Next layout: cards, compact, grid

Go to

/
Search
gthenh
Home
gthena
All
gthens
Subreddits
gthenl
Library
?
This list
Esc
Close a menu or this list

In the viewer

←or→
Previous / next file
↑or↓
Previous / next post
korj
Previous / next post
Space
Play / pause
m
Mute
z
Zoom
s
Save
o
Open the post (on its own page: back to it)
Esc
Close

Keys do nothing while you type in a box.