How can I remotely debug Magento 2 using xdebug when I do not have the “generated” files locally?
-
22-12-2020 - |
Question
I'm already familiar with xdebug, and debugging Magento 1 using it. Now that I'm working with Magento 2, I'm finding that my debugging sessions are failing with error messages like:
Cannot find a local copy of the file on server /my-magento-2-docroot/generated/code/Magento/Quote/Model/QuoteRepository/Interceptor.php
This is to-be-expected, since the code is on an actual server, running in "production" mode, with all dependencies compiled.
In Magento 1, the workaround for this was to simply not use code compilation, but I'm not sure if this is an option in Magento 2. Even when Magento 2 is in "developer" mode, it's trying to load files from the /generated
directory.
How can I debug a Magento 2 store without copying all of the generated code files down to my machine?
Solution
Short answer is: you can't. Xdebug needs the files to be there. Xdebug runs outside of Magento itself so it won't generate classes/files on your local filesystem.
FYI: the 'developer' mode allows Magento to create/save classes on the fly on an as-needed basis. These will still be saved to and loaded from the generated
directory. In 'production' mode Magento will disable this behavior (for performace reasons) and assumes the files will already be available in the generated
directory (and throws an exception if a file could not be found).
OTHER TIPS
To help anyone else facing this issue: My solution was to set up an SSH tunnel to allow me to reach the server that houses the Magento files (it's behind an AWS "bastion" server, in a virtual private cloud -- likely a common setup for other AWS users).
Step by step:
- SSH into the server that has the files on it, and give your SSH user read-only access by running:
setfacl -R -m u:eric:rX /path-to-magento2-files
- From your "AWS bastion" server, make a tunnel to that server
ssh -L 2232:server-that-has-magento-files:22 eric@your-aws-bastion-server.com
- (Optional but recommended) Edit your
~/.ssh/config
file locally to add an alias. This makes the rsync command more concise.Host dev7nfs HostName 127.0.0.1 Port 2232
- From your local machine, rsync the files into a local directory
rsync -rvz dev7nfs:/path-to-magento2-files/same-as-step-1 ~/magento2-sync
Now I'm able to point my phpstorm debugger to that local copy of the store, and each time I re-compile, I can re-run the rsync command to update my local debugging copy. Not ideal, but it works.
- Don't forget to replace
eric
with your own SSH username. - You don't have to use port 2232 locally. Any port will work as long as it's consistent.
- Instead of using
rsync
, you could mount that remote directory to your local filesystem if you want. This can be less than ideal due to latency/speed though.