Let's say that I have a back-end running on a customized PHP environment (no Laravel nor Symfony). It is used as an API server most of the time. But once a day I need to send out some mails. Let's say that I use a dedicated tools for that: Twig to create bodies of the mails, and PHPMailer to send them out. I don't need neither of these to answer the incoming front-end requests.
My question is: can I ask Composer (which I use as a dependency manager) to exclude Twig and PHPMailer when compiling the code to answer the front-end requests?
Obviously, the example here would save me fractions of seconds, and fractions of RAM, but what if I have other dependencies that are used only for other purposes too?
Obviously, the example here would save me fractions of seconds, and fractions of RAM
It actually does not save you nothing. Composer's autoloader loads class only when you request it. If you never use Twig or PHPMailer in your frontend request, it will never load it, so no RAM or CPU will be used.
Basically it already works in a way you would like to.
I think that you can reconsider the structure of your application. In case that you have 2 independent parts, they can be split into 2 php apps with they own composer.json. Common code can be loaded as a dependency.
Anyway, having unused dependencies is not a big issue and it has almost zero impact on performance. So, technically, the goal you want to achieve is more about purity of the code, not the performance optimisation.