Yeah, my company's website was developed by a completely different person in marketing that didn't work with the product development team. Unless the site is the product, for many companies it is such a low priority, it's basically just a contact info page and doesn't reflect on the quality of the product or dev team
That's basically testing that php works. Language features should be covered by the project already. Just like features of a particular library should be covered by that library's tests. At some point we need to assume that the tools work and have their own test coverage and focus on our own project
So true. I don't trust any developer that doesn't use a debugger or says it's not worth the effort to set up. It doesn't take much to get xdebug working, but even if it did it would still be worth it
I don't think I've seen any standard like that, and I'm not a big fan of Hungarian notation. Traits, interfaces and classes should be UpperCamelCase (aka PascalCase)
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
No problem. Leveraging DLX can make your worker code a lot less complex, and since it is handled by rabbitmq it can handle errors that happen outside of the worker's control. Definitely worth a look
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 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.
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
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
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
Write as many tests as you can against the existing functionality. Unit tests, end-to-end, whatever you can. The most annoying part of maintaining spaghetti code is all the regressions any time you refactor or change anything.
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
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.
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.
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
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
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.
Some config libraries like Zend\Config have adapters for many different config languages that can be parsed and merged into a common config object. Then you (and consumers of your orm library) can decide to use any config they want. No need to re-invent the wheel here.
Yeah, my company's website was developed by a completely different person in marketing that didn't work with the product development team. Unless the site is the product, for many companies it is such a low priority, it's basically just a contact info page and doesn't reflect on the quality of the product or dev team
That's basically testing that php works. Language features should be covered by the project already. Just like features of a particular library should be covered by that library's tests. At some point we need to assume that the tools work and have their own test coverage and focus on our own project
supervisor to run the workers + rabbitmq works for me
got it, i was picturing vendor directories that were somehow left over after removing the package through composer
how do you determine "unused vendor dirs"? packages that are not in composer.json? if so composer already removes those for you, what am i missing?
So true. I don't trust any developer that doesn't use a debugger or says it's not worth the effort to set up. It doesn't take much to get xdebug working, but even if it did it would still be worth it
My thoughts exactly. Magic and software don't mix
I don't think I've seen any standard like that, and I'm not a big fan of Hungarian notation. Traits, interfaces and classes should be UpperCamelCase (aka PascalCase)
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
No problem. Leveraging DLX can make your worker code a lot less complex, and since it is handled by rabbitmq it can handle errors that happen outside of the worker's control. Definitely worth a look
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.
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:
It uses a similar style for insert, update, delete. Also works well with Zend\Paginator to select ranges
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
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
Write as many tests as you can against the existing functionality. Unit tests, end-to-end, whatever you can. The most annoying part of maintaining spaghetti code is all the regressions any time you refactor or change anything.
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
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:
What to test:
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.
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
You could use satis to host your own repository of packages. Install it on the same machine and point composer to localhost
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.
You can use an ignored config file to store the key so it wont show up in your public repository.
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.
Some config libraries like Zend\Config have adapters for many different config languages that can be parsed and merged into a common config object. Then you (and consumers of your orm library) can decide to use any config they want. No need to re-invent the wheel here.
TIL! I'll definitely start doing this