Deferred image loading - Lazy Load plugins for WordPress. The best way to resolve plugins for PHP application sluggish plugin PHP

  • 20.06.2020

Function file - entertaining assistant in expanding the functionality of the site! Indeed, if used for its intended purpose, however, many blog / site owners wonderfully turn functions.php to the Solonka team.

In any case, there are feasibility and limitations (limitations, more often logical), and therefore some executable code, designed to adjust the parameters of the WP kernel (not the topic), more correctly out of the template ...

When the conversation is on the modernization of the functionality of the site, in the lineup of articles "without plugins ..." certainly advise to shove all code blocks into the legendary functions.php. It is not right!

All purely technical extensions (not relating to directly style template) is more logical to transfer the plug-in organized for their registration.

Create it! And also ceiling about the advantages and minuses (koim is significantly less) ...


Sections Articles:

how to create your plugin

in the text below, we learn how to create your own plugin as you hand: deal in all details, nuances. We learn what the pros and cons (minuses are less !! and rather, it is not at all disadvantages, but one or another feasibility for each administrator)

what is the difference between the Functions.php file from the plugin

Why should some code related directly to the site functionality, transfer to a separate plugin?

The most functions file, its goal and appearance is no different from the plugin (simply - the plugin in the subject))! - Its main task is to enrich the useful functionality (active) template.

For example, "NAVIGATION", where logically, the menu of the buttons is decorated CSS, respectively, the style of the active theme - may be more correct to leave in the root of the template.

What is the benefit - split the functions file to separate files or a separate plugin?

For example, the most banal - did you decide to change the template!? ... As a result - all the functional developments will disappear, because the entire useful code is located in the functions file (I saw such a file size 750klo)

Of course, you can transfer documentation of functions to a new topic, but - the cup of everything, without edit, which take away a lot of useful time, can not do: monkey and work)

And then:

site file download

Brief: The procedure for downloading the Site kernel files in our example is the active site plugins (from the plugins folder) and their content, and then the Functions.php file with content is processed. It's all milliseconds, and it is unlikely that there is a seriously talking about the winning the speed of pages.

Although it seems that one of the reasons for such an order of loading installed by developers where the second place is assigned to the functions file (as presumably More easily element), just the fact of the wide use of plugins, often massive content ...

Someone exclaim: another plugin ...? it's hard!

And I say, for no speed it will not affect ... rather, on the contrary, if it is thoughtful to create a site.

Moreover, the benefit of the transfer of some code is obvious in the other, namely, the site loading speed depends not on the number of active plug-ins, but from their contents! So why not reduce the function file that, as mentioned, is loaded a little later ..? And besides, it is a full-fledged massive plug-in template level! So where is the place of most of his code?

In my opinion, (active, working) template must contain only its parameters regarding specifically.

excursion to arithmetic ...

  1. it is loaded later, it is asked why not transferring where the code processing is performed primarily, and, respectively, set by the administrators of the WP kernel parameters will read faster and processed at the corresponding stage of the site startup.
  2. the notorious feasibility and logical organization of the site functionality.
  3. amenities that is not important!

In addition, as it was said, the functions file is the same plugin, "I will ask again, why is everything that in him to shove him? And in the process of working with the site, confused in a huge, difficult to read the document, which, by the way, is incredibly and unjustifiably will deal with its contents.

It's easier and more logical to create a light plugin, set up and forget ...

In short, everyone decides: to listen to his experience, or to the opinion of the author of some training article.

Then it follows the WordPress libraries, but not by articles ... From articles it is possible to draw only one idea ...

Somehow so here-s)

... for those who are interested:

examine all the rules of the kernel (and, by the way, the outlining of the loading directories)) can be wonderful in WordPress Codes.

... In one of the following articles just such a pheaker! ... and links to useful pages.


! .. Signing on Updates Website -
... break up with ignorance ..!

how to create a plugin of an additional file Functions.php

The posted plug-in, of course, is a simple solution, but the study should start from Azov!

Moreover, to achieve the goals taken in the article, no powerful plugins do not need!

We go into the hosting panel of the host (or FTP tools) open the file manager.

Open the plugins folder and create another directory in it (folder for files of our plugin). The name is absolutely any, in Latin. I have the name "Test" as an example.

Please note that the name of the plug-in admin will be such that is written in the Plugin Name: Test information header (see Comments).

Open the created folder and create the master plugin file in it:

... with the title, say my-functions.php and bring such lines to his body (and the file name can be absolutely any)

Rows in comments - information about the plugin, which will appear in the admin panel (plug-in menu).

Immediately after creating a folder and file, your plugin will appear in the admin. Look.

As an exe, you can activate it for a while - but nothing happens, the plugin is still idle.

That's all!! A simple plugin was created and, noteworthy, with their own hands for its own use (as Matroskin's cat used to say).

On this curtain of the presentation goes down ...
... Ramps dust sad lies ...

But by the way, and useful cinema from the TV series "Without plugins" - see, think if the code suggested in the video code in the functions file ??

Surely, you have repeatedly come across that you need to add some piece of code for your site on WordPress to add new functionality. I speak now not about the scripts of Google analysts that you insert into Header part of your topic. Not. I about those small fragments of the code that you found on the forums on the Internet and immediately ran to add them to your file functions.php..

Let's be honest, because you at least once did it, right? And this is understandable, because it has been written on the forum - add this code in functions.php your topic on WordPress.

The truth is that add each Internet found code in Functions.php - not always good idea. A safer decision will create your custom mini plugin with this code.

In this lesson, we will tell, in what cases you can add code to functions.php, and in which it is better to use a separate plugin. We also show how you can create a custom plug-in and add your code to it.

What is functions.php.

If you ever climbed on the files of your WordPress site, you could stumble into several Functions.php files. FUNCTIONS.PHP file, which we will talk about in this lesson are in the folder: WP-CONTENTHEMESBACH_MEMFUNCTIONS.PHP.

Obviously, this is the very file that stores all the functions and settings for your specific theme, active at the moment. Pay attention to the word "active", because in this and there will be the main message of this lesson.

Why always use functions.php is a bad idea

Do not understand incorrectly, use functions.php for small pieces of code in a couple of lines - this is a completely normal situation. We are talking about whether it is unwanted to use functions.php as a warehouse for absolutely all code you added. This is not a universal solution for any situation.

Cause №1.

If an update is displayed for your design theme, you will lose everything you add in the FunctionS.php file. I know what you just thought - but is it just for such situations?

Of course have. But there are also many people who have no idea what a daughter theme is. Or there are people who turned to you for help add a piece of code in their topic.

Therefore, this reason is on this list. If you add code to Functions.php without using a subsidiary, this is your first alarming bell.

Cause # 2.

Even if you set correctly and use a subsidiary. What happens if you want to go to another design topic? I hope you have added a comment on each change in your FunctionS.php file, because without this, the transition to another topic will be extremely painful. I think you caught a thought.

Cause number 3.

If you have added code to Functions.php, which completely unexpectedly broke your site completely, and you see an empty white screen - you will need an FTP client to download "spoiled" functions.php, edit it and download back to the site. Pleasure is herself.

When you can use Functions.php

Proper use of functions.php for a subsidiary, active at the moment is a permissible option. But remember, I focused on this word " active"?

If you add portions of the code that will make sense only in working with this topic specifically, then you can safely use functions.php (in a subsidiary). Here are some examples when it will be appropriate:

  • Adding another style file (.css) for your topic
  • Changing the length of the recording announcement (Post Excerpt) so that the site looks better
  • Adding custom fonts for current theme
  • Adding a localization file to translate current theme

In other words, every time you add or change something related to a specific current topic, you can safely use Functions.php.

When it is better to do without functions.php

Use functions.php to add more global things and functions that you theoretically can come in handy and for another topic - this is a bad idea.

Here are a couple of examples when it is better to do without functions.php:

  • Creating custom widgets that you will often use
  • Creating custom shortcodes
  • Adding a code that does not depends on the topic of registration (Google Analytics code, etc.)

In such cases, it is better to save this code regardless of your design topic. And you can do it with custom plugins.

Have you thought now - break your head over the creation of a plugin when you can edit functions.php? It is too difficult! Believe me, it is not. This is done very easily and quickly.

How to set up a custom plugin instead of functions.php

To create your custom plugin for storing your code, you need:

  1. Create a text file with your code and save it as .FP file
  2. Package received.php file V.Zip Archive
  3. Set this archive as a regular WordPress plugin in the menu Plugins → Add new

That's all, only 3 actions.

Step 1. Creating.PHP file with your code

Open a notepad on your computer and insert the following text:

Of course, you can use your name for plugin in the plugin name line:

Save the file and give it some kind of unique name so that WordPress does not confuse your plugin with the already installed. For example: WPCAFE-CUSTOM-FUNCTIONS.PHP.

Yes, do not forget when you save to select the type of files "All Files" and add the extension.php:

Step 2. Create.Zip Archive

I think there is no explanation here. Just create.zip archive with your file any convenient archiver.

Step 3. Install as an ordinary plugin

The simplest part. Just go to Wordpress Adminka in Plugins → Add new And download your archive as the most ordinary plugin.

As soon as you activate it, you can see your new plugin in the list of all other installed plugins:

How to add your code

To add your code fragment, simply insert it into the file.php that you created. Or you can always make another separate plugin for two different functions.

For example, this will look like your file.php, if you want to make a shortcode "Hello World!":

These comments do not affect the performance of your code and the speed of the plug-in. But you will be easier to navigate with them and remember that it makes every feature that you have added.

Just wrap your comment in the syntax from oblique and asterisks: /* your comment */

After making changes to your code, you can restart.php file via FTP or just create a new one.zip archive and download as a new plugin, and delete old.

Other ways to avoid edkes.php

By and large, if you are sure enough in your abilities and know how to add code in Functions.php, you should not have any difficulties and with custom plugins. There is nothing complicated here.

But we understand perfectly well, if you do not have a desire to mess with all this manually. Nevertheless, it is WordPress. Therefore, you can use the free Code snippets plugin, which makes it easy to add your additional code to the site:

With this plugin, you can add different snippets with the code, give them the name, description, activate and disconnect the selectively one or another snippet code.

Another cool feature is that you can import / export your code fragments between sites.

RESULTS

This may seem insignificant trifle, but the correct location of your additional code will allow you to switch between other design topics without any problems. You can also include or disconnect one functionality individually if you divide each additional function between individual plugins.

So, this method really deserves attention.

cMS MySQL (4)

I am trying to create a basic plugin system, similar to that you often find in CMS, such as WordPress. You have a plugin folder that are tied to the main system operation using notifications about events S. using design template Observer. or Event .

The problem is that the system can not know with what events The plugin wants to act - therefore the system should load each plugin for each page request to find out whether this plugin is really really needed at some point. It goes without saying, it is a lot of resources invested - in the case of WordPress, which adds to several additional MB of memory for each request!

Are there alternative ways to do it?

For example, is there a way to download all this once, and then cache the results so that your system know how plugins for lazy boot? In other words, the system loads the configuration file in which all the events are indicated that the plugin wants to tie, and then saves them into APC or something for future requests?

If it also works badly, then perhaps there is a special file structure that can be used to obtain reasonable assumptions about when some plugins are not needed to execute the query.

Answers

I have a plug-in management tool, but I use it only with procedural plugins and with all the included is usually loaded immediately. But for the API, based on events and lazy download, I could submit using small wrappers for controlling the plugins and resorting to automatic loading for actual extensions.

/ ** * API: WHATEVER * VERSION: 0.1 * TITLE: Plugin Example * Description: ... * Config: * Depends: OtherPlugin * / $ plugins ["title_event"] \u003d "TitleEventClass"; $ plugins ["Secondary"] \u003d Array ("Class2", "Callback"); ? \u003e.

In this example, I assume that the plug-in API is a simple list. This example of the FEATURE-PLUGIN-123.PHP script does nothing but add to the array when loading. Thus, even if you have a dozen plug-in features, it will only lead to an additional include_once to each.

But the main application / or the plug-in API may instead simply create instances of said classes (or New $ EventCB; for Raw- Call_user_Func_Array or call_user_func_array for callbacks). In turn, this will lead to the load of the actual task of the autoloader. Thus, you have a double system, where one part controls the list, the other is a real code.

Thus, I still imagine a simple config.php which simply lists plugins and settings like this:

"User / Wrapper-for-HTMLPURIFIER.PHP"); $ CFG ["Pretty"] \u003d 1;

Again, taking into account that it is just shell / data scenarios, with a description of the plug-in for controllability. You can also use the actual REGISTER_EVEN () API and define an additional wrapper function in each. But the list of class names seems like the simplest option.

The aforementioned control tool looks rusty and ugly: http://milki.include-once.org/genericplugins/
But it is not used if you only need a list (SQL table) and settings management. These overhead costs are intended only for the beautiful printing of the plug-in metadata and save config.php readable.

Finally:

sPL_AUTOLOAD () in include_path and a simple Event-\u003e Classname register, one script-shell each, just turns on everything at once.

I would save the name of the plugin class along with its signed events in the configuration file, and then saved the analyzed configuration file in APC, for example. Then, when the event starts, the system can lazy to load the corresponding classes of plug-ins as needed.

WordPress and other CMS systems are very bad examples.

We must understand that the modular, almost always means that it is harder.

The best scheme with which I ever worked to solve this situation is a class-based plugin, with a strict name agreement using the autoloader.

Thus, before using the plugin, you need to create an instance or use static functions.

You can even call the plugin:

eg:

"/plugins/($sparts)/($parts).php"); Break; ) // ...)?\u003e

As for events:

You must register this event statically to avoid dynamic change.

The database will be the right place for this. You can have events and install () and uninstall () methods in the plugin class to add certain events or binding methods to other events. This is one query to the database, and if you want to get more from it, add it to memcached or in a flat ini file.

Works well for me. Thus, I managed to get a heavy system that consumed 8 MB to request to fall up to 1 MB, with exactly the same list of functions, without prior caching. Now we can add more features and maintain the system "clean"

i hope this will help

The best way is to start coding with them. Design templates are an excellent concept that is difficult to apply, just reading them. Take a few examples of implementations that you find on the Internet and create around them.

An excellent resource is the "Data and Object" page. They browse patterns and give you both conceptual and real examples. Their reference material is also wonderful.

This is the main file in your WordPress theme. Located in / WP-CONTENT / Themes / (here is the name of your topic) /functions.php.
It defines the important properties of the topic, the hooks, appearance and its functionality are customized, and some of the functions you need are added. This file is loaded every time you open any WordPress page, so you can change any element of the site with it. In this regard, many tips a la " how to change something in WordPress without plugins »Often concern exactly making changes in functions.php, instead of creating a separate plug-in to this functionality or use the finished solution. Often this leads to the information overload of this file, the code becomes hard to disassemble, and it is even more difficult to make corrections. But this is not the most dangerous. The most dangerous is that when a survey is changed, part or all the necessary site functionality will disappear.

What is the difference between functions.php from the plugin

. In essence, FUNCTIONS.PHP is a kind of global unclusive plugin, which is tied to the current topic. As it connects to WordPress, you can see WP-settings.php. As can be seen from the source code, its download occurs after all plug-ins, however, this does not give any drawbacks or advantages, except for the ability to override something in the plugins connected. For the speed of the code, it will not affect anybody. Only the content of plugins and functions.php affects. Therefore, be careful when choosing active plug-ins for your theme and give up unnecessary, unnecessary to you, then you can easily facilitate your site and speed up his work.

When you need to use functions.php

Follow the following rule: if the functionality is directly related to the current topic, but not with the site work, write it to functions.php.

For example, it may be

  • Setting miniature
  • Setting sizes Schidbarov
  • Setting the places for the widgets
  • Announcement of places for navigation menu
  • Topics settings
  • Additional features of your topic

When to avoid using functions.php

If the functionality should work even with a change of an active topic, it is worth taking care of its submission to a separate plugin.
This can be attributed:

  • Definition of Attendance Counters (Google Analytiys, Yandex.Metrika, LiveInternet)
  • Adjust the additional admin functionality (for example,)
  • Configuring the source code ()
  • Definition of shortcodes
  • check in

Incomplete lists, you can define their content yourself for yourself.

Where to make this code, if not in FUNCTIONS.PHP? You can write special plugins to them, however, there is a way more interesting and easier.

mu-plugins as an alternative to functions.php

To us in the modern versions of Wordpress from WordPress Mu (Multi-User) came interesting functionality, called Mu Plugins.. Its essence was as follows. The WordPress MU administrator sometimes required to define plugins for the entire network of sites. It was not possible to achieve the usual functionality, so they introduced a special section: / WP-content / Mu-plugins /, where they were determined. Another interesting, plug-in files from this directory are loaded before all the others, which makes it possible to predetermine some constants or settings.
Later WPMU abolished, its code was integrated with the main blog, and now any WordPress can use the MU-Plugins functionality, which is now deciphered as Must Use., that is, mandatory for use.

How to use mu-plugins

First you need to create a special section / WP-CONTENT / MU-PUGINS /
In it we place the desired plug-in files. Unlike conventional plug-ins, it is not necessary to withstand a special syntax, and the functionality can be announced directly

Here for example, a file has been created with the code of attendance counters.
Inside this file looks like this

// ... Instead of this line, insert the counters code ...

In the admin he will look like Necessary

8 Replies

You can use the OBServer template. A simple functional way to perform this:

Output:

This is My Crazy Application 4 + 5 \u003d 9 4 * 5 \u003d 20

Notes:

In this example, the source code you must declare all your plugins before the actual source code you want to extend. I included an example of how to handle one or more values \u200b\u200btransmitted by the plugin. The most difficult part of this is to write the actual documentation, which lists which arguments are transmitted to each hook.

This is just one way to create a plug-in system in PHP. There are the best alternatives, I suggest you familiarize yourself with WordPress documentation for more information.

Sorry, it seems that the underscians are replaced by HTML Markdown objects? I can re-publish this code when this error will be fixed.

Edit: Nevermind, it appears only when you edit

So, let's say, you do not need the OBServer pattern, because it requires that you change the class methods to handle the listening task and want to get something in common. And let's say you do not want to use EXTENDS inheritance, because you can already inherit your class from some other class. It would be nice to have a general way to make any class connected without much effort? Here's how:

_Class \u003d get_class (& $ refobject); $ this -\u003e _ refobject \u003d $ refobject; ) Public function __set ($ sproperty, $ mixed) ($ splugin \u003d $ this -\u003e _ class. "_". $ sproperty. "_setevent"; if (IS_CALLABLE ($ Splugin)) ($ Mixed \u003d Call_user_Func_Array ($ Splugin, $ mixed);) $ this -\u003e _ refoobject -\u003e $ sproperty \u003d $ mixed;) public function __get ($ sproperty) ($ AsiTems \u003d (Array) $ this -\u003e _ refoobject; $ Mixed \u003d $ AsiTems [$ sproperty]; $ SPLUGIN \u003d $ this -\u003e _ class. "_". $ sproperty. "_getevent"; if (IS_CALLABLE ($ Splugin)) ($ Mixed \u003d Call_user_Func_Array ($ Splugin, $ Mixed);) Return $ Mixed;) Public Function __Call ($ Smethod, $ Mixed) ($ splugin \u003d $ this -\u003e _ class. "_". $ SMETHOD. "_BeForeEvent"; if (is_callable ($ splugin)) ($ Mixed \u003d Call_user_Func_Array ($ Splugin, $ Mixed);) if ( $ Mixed! \u003d "block_event") (call_user_func_array (array (& $ -\u003e _ refoobject, $ smethod), $ mixed); $ splugin \u003d $ this -\u003e _ class. "_". $ SMETHOD. "_Afterevent"; if ( is_callable ($ Splugin)) (Call_user_Func_Array ($ Splugin, $ Mixed);)))) // END CLAS PLUGIN CLUGGABLE EXTENDS PLUGIN () // END CLASS PL uggable ///////////////// // //////////////// /////////////////////////////// // Name \u003d ""; Public Function Bark (& $ Show) (Echo "$ Show
\\ n ";) Public Function Sayname () (Echo"
\\ NMY Name IS: ". $ This-\u003e Name."
\\ n ";)) // End Class Dog $ Dog \u003d New Dog (); ///////////////// // // part 3 //////// //////////// $ pdog \u003d new pluggable ($ DOG); Function Dog_bark_beforeEvent (& $ Mixed) ($ Mixed \u003d "Woof"; // Override Saying "MEOW" with "Woof" / / $ Mixed \u003d "block_event"; // if you want to block the event return $ mixed;) Function Dog_Bark_Afterevent (& $ Mixed) (Echo $ Mixed; // show the override) Function Dog_name_seTevent (& $ Mixed) ($ Mixed \u003d "Coco"; // override "fido" with "COCO" RETURN $ Mixed;) Function Dog_Name_GeTevent (& $ Mixed) ($ Mixed \u003d "Different"; // Override "Coco" with "different" Return $ Mixed;) ///////////////// // ////////////////////// $ PDOG-\u003e NAME \u003d "FIDO"; $ PDog-\u003e BARK ("MEOW"); $ PDog-\u003e Sayname (); Echo "My New Name IS:". $ PDOG-\u003e NAME;

In the first part, that you can enable with the request_ONCE () call at the top of your PHP script. It loads the classes to do something connected.

In part 2, where we download the class. Note. I did not need to do anything special for a class, which is significantly different from the OBServer template.

In part 3, where we switch our class to "connected" (i.e., we support plugins that allow us to override the methods and properties of the class). So, for example, if you have a web application, you can have a register of plugins, and you can activate plugins here. Note also on the Dog_Bark_BeForeEvent () function. If I installed $ mixed \u003d "block_event" in front of the RETURN operator, it will block the dog from Laya and also blocks Dog_Bark_Afterevent, because there will be no event.

In part 4, that the normal operation code, but note that what you might think will not work. For example, the dog does not declare it with the name "FIDO", but "COCO". The dog does not say "meow", but "Worth". And when you want to see the name of the dog later, you will find that it is "different", and not "Coco". All these overrides were presented in part 3.

So how does it work? Well, let them exclude eval () (which everyone says "evil") and exclude that this is not the ObServer pattern. Thus, the way it works is a hidden empty class called pluggable, which does not contain methods and properties used by the DOG class. Thus, as this happens, the magic methods will be involved for us. Therefore, in parts 3 and 4, we communicate with the object obtained from the class Pluggable, and not with the DOG class itself. Instead, we allow the Plugin class "touch" the DOG object for us. (If this is some kind of design that I do not know - let me know.)

The method of hook and listener is most commonly used, but there are other things you can do. Depending on the size of your application and who wants to see the code (it will be a FOSS Script, or something in the house) will greatly affect how you want to resolve the plugins.

kdeloach has a pleasant example, but its implementation and Hook function are a little unsafe. I would ask you to give more information about the character of PHP applications for your letter, and how you see plugins.

1 to Kdeloach from me.

Here is an approach that I used is an attempt to copy from the Qt signals / slots from the Qt mechanism, a kind of OBSERVER template. Objects can emit signals. Each signal has an identifier in the system - it consists of an ID ID + object-sender. Each signal can be tied to receiver, which is simply "called", you use the tire class to transmit signals to anyone who is interested in getting it when something happens You send a signal. Below is an example and an example of implementation.

login (); ?\u003e

I believe that the easiest way is to follow Jeff's advice and look at the existing code. Try to see Wordpress, Drupal, Joomla and other famous PHP-CMS to see what their API interfaces look and feel. Thus, you can even get the ideas that you may not have thought before to make things a little more thick.

A more direct response would be to write common files that they would be included in the include file to provide ease of use. It will be divided into categories and is not provided in the same "Hooks.php" Massive file. Be careful because what ends is that the files that they include ultimately have more and more dependencies and functionality. Try to limit the addance API. I.E fewer files for their inclusion.

There is a neat project called