Phpstorm файл с настройками
В продолжение предыдущей статьи, хотел бы поведать о том, чем же он так круче остальных IDE и редакторов, какие именно его особенности позволяют мне ежедневно экономить время на разработке и работать эффективнее.
Навигация
У вас есть почти мгновенный поиск по всему проекту. Если хотите найти абсолютно любую строку — жмете Ctrl+Shift+F — в диалоговом окне вводите нужную строку, и IDE находит вам все вхождения данный строки в проекте. Эдакий аналог grep, только интереснее — в результатах поиска IDE классифицирует найденное вхождение строки, указывает в каких файлах и в какой строке, сколько раз встречается искомая подстрока.
Но не всегда удобно искать именно строку. Часто мы знаем, что ищем именно класс или функцию, или какую-либо другую сущность в понятии phpStorm. Для поиска везде и вся подобных сущностей существует хоткей Shift*2 — всплывающее окно поможет быстро перейти к какой-либо сущности.
Про полезные хоткеи я когда-нибудь напишу отдельный пост, попробуйте сами посмотреть в документации и поэкспериментировать с ними.
Кроме упомянутых выше возможностей поиска, можно удобно ориентироваться внутри открытого большого файла. Иногда бывают ситуации, когда нужно отредактировать какой-то кусок кода, перейти к другому в этом же файле, пролистав глубоко вниз, а затем вернуться обратно. Крутить колесо — долго и муторно. Поэтому можно вернуться к предыдущему редактируемому куску хоткеем Ctrl+Alt+Shift+вверх или вниз. Также есть GUI стрелка, которую можно вызвать, кликнув по маркеру, который добавляется напротив отредактированной строки — появится контекстное меню встроенной системы контроля изменений phpStorm, где кликом по стрелке можно перейти к отредактированным областям
Крайне удобной для меня оказалась возможность мгновенного перехода к определению сущности, если зажав ctrl кликнуть по ней в редакторе — супер удобно! Если у сущности определен phpDoc комментарий, то можно просмотреть его через ctrl+Q, опять же когда курсор мыши над сущностью. Поэтому коллеги — обязательно комментируйте все свои наработки с помощью phpDoc — это совсем не сложно, тогда как всем остальным это может сильно упростить жизнь.
Кстати о phpDoc — есть его полная поддержка. После написания функции или метода, например, достаточно написать над функцией строку /** и нажать tab — основной блок для phpDoc комментария будет сгенерирован. Вам нужно будет только добавить описание для вашей сущности и задать типы переменных (в случае с функциями). В случае изменения функции, ее параметров или чего либо, что могло бы повлиять на phpDoc — редактор подсветит блок комментария и предложит обновить его.
Вообще говоря — phpStorm всегда будет помогать вам, подсвечивая или подчеркивая какие-то странные на его взгляд моменты. Лучше обращать на них внимание и следовать рекомендациям.
Вернемся к навигации. Введя простой хоткей Ctrl+L можно быстро перейти к определенной строке и символу в документе. Нужно ввести номер строки и номер символа (если надо) через двоеточие.
Есть еще одна крутая вещь — навигатор по структуре файла. Если файл структурирован (html/xml, css или php класс, например), то такой файл можно просмотреть в виде древовидной структуры. Это крайне полезно при разработке классов, т.к. клик по названию метода в этом дереве производит быстрой переход к методу, да и наглядно видно. какие методы с какими данными и в каком контексте работают.
Аналогичное дерево можно вызвать во всплывающем окне над редактором с помощью ctrl+f12, а чтобы добавить его в левую панель, нужно зайти в меню View -> Tool Windows -> Structure
File watchers
Всем известно, что для клиентской оптимизации надо сжимать js и css файлы. Однако, когда процесс выкладки на продакшен сервер не налажен, приходится делать оптимизацию скриптов и стилей вручную, например, с помощью google closure compiller в онлайне или локально. Данный инструмент позволяет автоматизировать подобные процессы. Если говорить грубо — инструмент следит за определенными файлами, и как только поступают какие-то изменения в файл, он сразу же извлекает команду, которая делает какое-то действие. Например для сжатия js файлов можно настроить File Watcher’а так, чтобы при каждом изменении файла он создавал его копию с суффиксом .min.js, в котором будет содержаться сжатая копия файла.
На самом деле инструментов гораздо больше, чем я тут описываю. Тут тебе и vagrant для разворачивания виртуалок, и composer для добавления в проект библиотек из этого замечательного менеджера пакетов, и интеграция с PHPUnit, Behat, для организации TDD и BDD, и возможности рефакторинга, и еще многое многое другое, всего в рамках одного поста не описать. Но буду касаться иногда разных классных инструментов в последующих своих постах, т.к. есть еще много всего, о чем хотелось бы написать.
1 Answer 1
Where are the files stored, so I can back them up manually?
There are 2 kinds of settings and they all need to be backed up separately (especially since you have PC crashes):
Specific project settings -- stored in .idea subfolder for each project.
IDE-wide settings -- stored separately and that's what File | Export/Import Settings. works with.
Each major version stores IDE settings in own folder. This allows to run more than one version of the same IDE in parallel (typical case: stable version and EAP of the next major version: e.g. right now it would be 2018.1 and 2018.2 EAP).
Project settings:
That's your Run/Debug Configurations, project-specific dictionaries, deployment entries, Scopes and more.
If you are the only one person who works on this project -- you may add it to your VCS (if it's OK, of course), otherwise backup normally at the end of the day.
Copy global settings to the project level
Global (IDE) settings are stored separately from projects. That is why, these settings are not shared through version control together with the project.
Some settings, however, can be copied to the project level. For example, you can create a copy of your or inspection profiles. If you do so, the IDE creates the corresponding configuration files in the .idea directory that you can share together with the project through VCS.
PhpStorm also provides several ways of sharing settings between different IDE instances. See Share IDE settings for details.
Besides the standard options available , PhpStorm enables you to perform low-level configuration of the underlying platform and the Java runtime.
This may lead to unexpected problems and make your PhpStorm installation inoperable if you are not sure what you are doing. Contact JetBrains Support for instructions regarding the options and values that might help you with whatever issue you are trying to solve.
JVM options
PhpStorm runs on the Java Virtual Machine (JVM), which has various options that control its performance. The default options used to run PhpStorm are specified in the IDE installation directory:
Do not change JVM options in the default file, because it is replaced when PhpStorm is updated. Moreover, in case of macOS, editing this file violates the application signature.
Locate the JVM options file
If you are not sure where PhpStorm is getting its JVM options, check the following:
The location specified by the PHPSTORM_VM_OPTIONS environment variable. If the specified file exists, it will override all other JVM options files.
If the Toolbox App manages your current PhpStorm instance, open the Toolbox App, click next to the relevant IDE instance, and select Settings . Under Configuration , find Java Virtual Machine options and click Edit .
If you are running a standalone PhpStorm instance, check the configuration directory.
If there are no JVM options files defined in the previous locations, PhpStorm will use the default JVM options file. Do not modify it. Use it only to check what are the default options that PhpStorm uses.
Ну и плагины
Для того, чтобы найти нужный плагин, необходимо зайти в File — Settings — IDE Settings — Plugins. На этой странице показан перечень установленных плагинов. Кнопка Browse Repositories … отправит вас в список всех возможных плагинов.
phpStorm идет уже с набором предустановленных плагинов, но я напишу, что стороннего устанавливал я.
Project settings apply to the current project only. They are stored together with other project files in the .idea directory in XML format.
For example, project settings include VCS settings, code style settings, the list of language injections, and so on. You can add these settings to your VCS along with other project files.
To configure project settings, select PhpStorm | Preferences on macOS or File | Settings on Windows and Linux from the main menu. Alternatively, you can press Ctrl+Alt+S to show the IDE settings.
In the Settings/Preferences dialog, project settings that apply only to the current project are marked with the icon. Other settings are global and apply to all existing projects.
If you want to share project settings between already existing projects, you can use the Settings Repository or the Settings Sync plugin. You can also export the settings to a ZIP archive and import it later to other IDE instances.
Restful Tester
Перед началом работы с каким-то внешним API хочется попробовать предоставляемые методы вживую. Да и при отладке необходимость быстренько составить запрос с авторизацией возникает. Однако не имеет смысла писать какой-то код — можно воспользоваться соответствующими инструментами. Ранее я пользовался для этого плагином для Chrome — Postman, однако теперь нужды в нем нет, я могу сделать запрос прямо из IDE.
Common properties
Users often change the location of the default IDE directories. For more information, see Change the location of IDE directories.
Limits that can affect performance:
Maximum size of files (in kilobytes) that PhpStorm is able to open. Working with large files can affect editor performance and increase memory consumption. The default value is 20000 .
Maximum size of files (in kilobytes) for which PhpStorm provides coding assistance. Coding assistance for large files can affect editor performance and increase memory consumption. The default value is 2500 .
Maximum size of the console cyclic buffer (in kilobytes). If the console output size exceeds this value, the oldest lines are deleted. To disable the cyclic buffer, set idea.cycle.buffer.size=disabled .
Maximum size (in kilobytes) that PhpStorm loads for showing past file contents when comparing changes. The default value is 20480 .
PhpStorm provides a number of other properties that define interaction with the environment (window managers, launchers, the file system, and so on). Most of them act like hidden settings (in the sense that they are not evidently exposed), which you may need to enable or disable in certain cases. Change these properties only if advised by JetBrains Support.
Добрый день, где в PHPStorm лежат все его настройки, чтобы при переходе на другое рабочее рабочее место можно было быстро восстановить свои хоткеи сниппеты и т.п.
И как вы реализуете их сохранение бекап и т.п.
Оценить 1 комментарий
File -> Export Settings
UPD: Ну а сейчас и вовсе штатно в облако они сохраняются.
я сделал гит репозиторий удаленный, создал проект из его конфига в нём же самом
после каждого изменения настроек комичу и пушу
DevMan: это может быть оправданно, если настроить автокоммит при изменении файлов. А то я бывает месяцами настройки не бэкаплю.
P.S. Но у меня автокоммит никак не получалось настроить когда-то для другой задачи.
Алексей Уколов: не знаю, как по мне - дичь: настройки не меняются по 20 раз в день.
ну если автора устраивает, то good for him.
DevMan: я задолбался терять конфиг. например если свет вырубается на секунду, то если шторм чето писал в этот момент в конфиг то он становится не корректным и слетает на дефолт, я в нем не разбираюсь и вручную чинить его не умею. зато как упадет потом целый месяц чего-то привычного не хватает и приходится заново настраивать, макросы всякие, разукраски, хоткеи свои. че-то новое я там делаю редко поэтому совершенно несложно открыть этот проект, нажать 3 кнопки и быть спокойным. и так мне больше нравится чем копипастить папку с конфигом на компе. +на удаленном надежнее
какой вариант проще предложите?
DevMan: если вы штатный импорт/экспорт имеете в виду то я от него отказался, правда последний раз пробовал в 6-м вроде, импорт был кривым, часть настроек терялась куда-то
Алексей Уколов: автокоммит там если только выборочно, он постоянно что-то пишет в него. вот например закрыл окно с проектом, 2 файла поменялось
по свету ничего не скажу: 1. система итак автоматически создает инкрементальные бекапы каждый час; 2. ни разу мне не везло поймать какой-то фейл в процессе записи конфига.
повторюсь: для меня этот способ - дичь. но если он вас устраивает, то норм.
I occasionally lose all my PhpStorm settings and projects when my PC crashes. File -> Export either doesn't back up everything, or File -> Import doesn't work.
I have custom everything - layout, syntax coloring, shortcuts, PHPUnit configs. Mostly none of this is set after a crash when opening the same project folders.
Where are the files stored, so I can back them up manually?
what exactly about my trying File -> Export and File -> Import makes you think I haven't tried exporting and importing settings?
Отладка
Одна из самых крутых возможностей современных php IDE — возможность отладки. Про это я тоже напишу отдельный пост. Это крайне удобная вещь — кто кодил на компиллируемых языках в IDE (например в Visual Studio, или какой-нибудь Delphi) — тот меня поймет. Можно пошагово прогнать свое приложение, выяснить как ведет себя приложение на том или ином этапе работы, поддерживаются брейкпоинты, можно просмотреть стек вызовов для каждого момента времени, просмотреть и даже подменить значение переменных! Все это очень круто и сильно ускоряет процесс отладки. Даешь бой print_r’ам и var_dump’ам! (шутка, конечно и о них забывать не стоит). Must have для php разработчика.
Также, если вы пользуетесь профилированием от xdebug, то в phpStorm встроен анализатор логов профайлера. Можно загрузить файлик в IDE, просмотреть там лог вызовов, и тут же перейти к нужным функциям, отрефакторить их и т.д. Круто!
Configure platform properties:
Do one of the following to create an empty idea.properties file in the configuration directory that will override the values from the original file:
From the main menu, select Help | Edit Custom Properties .
If you do not have any project open, on the Welcome screen, click Configure and then select Edit Custom Properties .
If you cannot start PhpStorm, manually create an empty idea.properties file in the PhpStorm configuration directory.
If you do not have write access to the PhpStorm configuration directory, you can add the PHPSTORM_PROPERTIES environment variable to specify the location of the idea.properties file. The properties in this file will override the corresponding properties in both the original default file and the one located in the PhpStorm configuration directory.
Редактор
Казалось бы, о чем тут можно рассказать. Ну — редактор, ну — синтаксис подсвечивает, красиво, ага. Но и другие редакторы в этом плане не отстают. Но я все-же выделю несколько фишек, которые либо в других редакторах не работают, либо работают кривовато:
К минусам редактора могу отнести некоторую тормознутость.
Бывают глюки, при которых невозможно по неведомой причине сменить кодировку файла (очень редко). Иногда бывает глюк, что убираешь какую-то кавычку в строке, шторм сразу же меняет подсветку дальнейшего кода, но если поставить кавычку обратно, то он может предыдущую подсветку не сменить.
Еще мне откровенно не хватало minimap файла после Sublime Text, но как оказалось — есть плагинчик, называется CodeGlance.
Еще, к сожалению пока не могу найти, как сделать автокомплит по произвольным строкам (ключи массива например) 🙁
Common options
The default values of the JVM options should be optimal in most cases. The following are the most commonly modified ones:
Limits the maximum memory heap size that the JVM can allocate for running PhpStorm. The default value depends on the platform. If you are experiencing slowdowns, you may want to increase this value, for example, to set the value to 2048 megabytes, change this option to -Xmx2048m .
Specifies the initial memory allocated by the JVM for running PhpStorm. The default value depends on the platform. It is usually set to about half of the maximum allowed memory (-Xmx), for example, -Xms1024m .
Specifies the ratio between the size of the young and old generation of the heap. In most cases, a ratio between 2 and 4 is recommended. This will set the size of the young generation to be 1/2 to 1/4 of the old generation correspondingly, which is good when you are often working on one project and only a few files at a time. However, if you are constantly opening new files and switching between several projects, you may need to increase the young generation. In this case, try setting -XX:NewRatio=1 , which will make the young generation as large as the old generation, allowing objects to remain in the young generation for longer.
For more information about the available JVM options, see the java command reference.
Интеграция с инструментами разработки
Все полезные для себя интеграции я рассмотрю отдельно, т.к. каждый про каждый инструмент можно написать многое. А сейчас только поверхностно пробегусь по тому, что использую я в своей работе.
Куда ж без него. До моего знакомства с phpStorm я активно использовал продукт Atlassian SourceTree, который по мнению множества разработчиков считается одним из лучших OpenSource продуктов в данном сегменте. Не могу ничего сказать плохого в адрес этого инструмента, он до сих пор служит мне верой и правдой, с удовольствием использую его каждый день. Но и в phpStorm есть возможность работать с репозиторием, и некоторые аспекты сделаны удобнее, чем в SourceTree. При включении интеграции с git в phpStorm появляется чейнджер веток (правый нижний угол), в тулбаре changes (ctrl+9) можно отслеживать изменения файлов, просмотреть diff для файла, оттуда же сделать коммит и push. На вкладке log этого тулбара можно просмотреть дерево коммитов
Default settings for new projects
You can configure project settings not only for the current project, but for all projects that you will create later. This means that you can set the new default settings for your projects.
From the main menu, select File | New Projects Setup | Settings/Preferences for New Projects .
Platform properties
PhpStorm enables you to customize various platform-specific properties, such as the path to user-installed plugins and the maximum supported file size. The default properties used to run PhpStorm are specified in the IDE installation directory:
Do not change platform properties in the default file, because it is replaced when PhpStorm is updated. Moreover, in case of macOS, editing this file violates the application signature.
Configure JVM options
Do one of the following to create a copy of the default file with JVM options in the configuration directory that will override the original file:
From the main menu, select Help | Edit Custom VM Options .
If you do not have any project open, on the Welcome screen, click Configure and then Edit Custom VM Options .
If you cannot start PhpStorm, manually copy the default file with JVM options to the PhpStorm configuration directory.
If you do not have write access to the PhpStorm configuration directory, you can add the PHPSTORM_VM_OPTIONS environment variable to specify the location of the file with your preferred JVM options. This file will override both the original default file and the copy located in the PhpStorm configuration directory.
If you are using the Toolbox App, it manages the installation and configuration directory and lets you configure JVM options for every IDE instance. Open the Toolbox App, click next to the relevant IDE instance, and select Settings .
List of non-shareable configuration files
PhpStorm identifies configuration files and adds them to the list of ignored files automatically. However, if you are sharing your project manually, we recommend that you avoid placing these files and folders under version control:
Share project settings through VCS
This information is valid for Git and Mercurial. If you use another version control system, refer to How to manage projects under Version Control Systems for information on how to share projects manually.
Project settings are stored in the project directory as a set of XML files under the .idea folder. This folder contains both user-specific settings that shouldn't be placed under version control and project settings that are normally shared among developers working in a team, for example, the code style configuration.
When you place a project under version control, your personal settings are automatically ignored. PhpStorm moves workspace.xml — the file with your personal settings — to the list of ignored files to avoid conflicts with other developers' settings.
Configuration files are processed according to your choice. Once you modify the project settings, and a new configuration file is created, the IDE shows a notification at the bottom of the screen prompting you to select how you want to treat configuration files in this project:
View files : view the list of created configuration files and select, which of them you want to place under version control. After that, the selected files will be scheduled for addition to VCS.
Always Add : silently schedule all configuration files created in the .idea directory for addition to VCS (applies only to the current project).
Don't Ask Again : never schedule configuration files for addition to VCS; they will have the unversioned status until you manually add them to VCS (applies only to the current project).
If you close the notification without selecting any option, it will appear again after a new configuration file is created. The new file will also go to the list that will be there until you select one of the options even if you restart the IDE.
If the misc.xml or the .ipr file is already under version control, project configuration files are silently scheduled for addition to VCS.
SSH консоль
Раньше пользовался Putty, теперь пользуюсь встроенной консолью в phpStorm. Для подключения к серверу нужно пройти в меню Tools -> Start SSH Session …. Появится всплывающее окно, предлагающее подключиться к одному из существующих серверов, забитых в настройках, либо сделать одноразовое подключение (к сожалению. не сохраняется, или я просто пока не знаю как его сохранить 🙁 ). Удобно, не выходя из IDE, можно работать с консолью на сервере.
IDE-wide settings:
File | Export/Import Settings. should handle it (at very least config files made by IDE core). But it needs to be run manually . so inconvenient to use regularly, that's for sure.
All settings are stored in individual XML files so easy to backup and restore. On Windows and Linux that will be just one folder to backup; on Mac -- two (as Preferences and Plugins are stored separately).
For example on Windows you would need to backup this folder in full: C:\Users\USERNAME\.PhpStorm2018.1\config (that's for 2018.1 version). Other sibling folders (like system ) can be ignored -- that's where indexes/caches are stored -- they can be regenerated at any time.
P.S. If you have folders from older IDE versions that you do not have any more and do not plan to use again -- just delete them (make backup first if desired, of course).
Читайте также: