How to set up smartphones and PCs. Informational portal
  • home
  • Programs
  • Chatty section php. Creating functions with a variable number of arguments

Chatty section php. Creating functions with a variable number of arguments

An article that discusses HTML section element from the sectioning category.

Purpose of the section element

The section element is used to create a section in a document that groups some topical content together. For each section in the document, its title (subject) should be indicated. This is usually done with headings (h1 - h6 elements).

Section heading

Section content...

section elements are typically used in the following cases:

  • to mark up sections within a section. For example, to mark up chapters in an article, tabs in a dialog box, sections in a dissertation, etc.
  • to group multiple sections into one thematic group. For example, to group latest news on the site, comments on the article, etc.

Thus, the section element should only be used for some content if it has a heading and is part of something else.

Applying the section element

For example, consider a page code snippet containing an article with comments. Each of the comments left by the user on the page contains some completed content and can therefore be considered an article element. But, at the same time, all comments represent some topic group, and therefore they can be placed in the section element, i.e. given element will group all those comments on the page together.

Article title

Comments

Comment title

Comment text...

Comment title

Comment text...

Title of the article Comments Title of the comment Title of the comment

For example, consider using section elements to create sections within an article element:

Book title

First chapter

Second chapter

Third chapter

Annex A

Annex B

The above example would have the following structure (outline):

Book Title First Chapter Second Chapter Third Chapter Appendix A Appendix B

Restrictions when using the section element

The section element in HTML 5 is not a generic element for grouping content; it should not be used to wrap any content you like. Its main purpose is to add semantics to the document and create its structure (outline).

When an author needs to group content just to style it or work with it in JavaScript, the best thing to do is use the div element. The div element, unlike the section element, does not add semantics to the document and does not participate in the creation of its structure (outline).

Difference between section and article elements

The section and article elements, while seemingly very similar, have different semantic meanings. The article element is for grouping content that is complete, standalone, and can be considered separate from the rest of the page's content. And the section element has a different semantic meaning, it is intended to group content that is an integral part of something else.

But how does an author know what some content on a page is? Let's look at this using an example article fragment. A fragment is part of an article and, therefore, the section element must be used to group its content. But the same fragment, already left as a commentary, will be something whole, complete. Therefore, in this context, the article element can be used to group it. But, of course, the opposite can also be argued. Therefore, which element to use to group content in most cases depends on your subjective opinion as an author. But the most important thing in this approach is to maintain the chosen position. Therefore, the more consistent the author is in creating the structure, the more sense he will be able to put into it.

Templates in Bitrix can be divided into several types:
  • Common and Complex Component Templates 2.0
  • Site Templates
  • Templates for other entities (mailings, newsletter releases, web forms, export generators, and much more)

Component templates even have the ability to use template engines. In principle, you can connect any template engine, but there are no auxiliary tools out of the box. If anyone needs it, I have a couple of links to extensions for twig and blade , which work and are quite used in production. But even here Bitrixoids perverted. The template engine can only be used with components. Connecting the template engine to the site template renderer, or other entities will not work, because. there is no renderer there.

In component templates, another point with their placement is annoying. The component is connected using a simple design
$APPLICATION->IncludeComponent("bitrix:catalog.section", "template_name", );
The second parameter is the name of the component template. So, depending on various conditions, the location of this template can be in the most unexpected places:

  • bitrix/components/bitrix/catalog.section/templates/template_name
  • local/components/bitrix/catalog.section/templates/template_name
  • bitrix/templates/.default/components/bitrix/catalog.section/template_name
  • bitrix/templates/site_template/components/bitrix/catalog.section/template_name
  • local/templates/.default/components/bitrix/catalog.section/template_name
  • local/templates/site_template/components/bitrix/catalog.section/template_name
  • bitrix/components/bitrix/catalog/templates/.default/bitrix/catalog.section/template_name
  • local/templates/site_template/components/bitrix/catalog/.default/bitrix/catalog.section/template_name
And I haven't listed all the options yet...

A site template can be viewed as a set of files: header.php, footer.php (yes, the site must have them), description.php ( system description site template), template_styles.css (site template styles), a directory with component templates, and a group of less important files. And that's it. And there is no way to influence it, nothing to do with it. Unable to hook template engine.

There is nothing to say about other templates. They are either simply stored in the database in the form of layout with the inclusion of some "variable" data in it, or it's stupid php file, which does all the work, from fetching parameters from the database to displaying information. For example, you can look at the YML file generator for the market. There is no point in posting it here, simply because it is quite large, about 2k lines. Whoever needs it, google it, it lies in /bitrix/modules/catalog/load/yandex_run.php

File nature

As it became clear above, everything is not very good in Bitrix with architecture. But Bitrix also has another important aspect of architecture.
Bitrix is ​​a half-file CMS. A lot of things are controlled using some kind of files:

  • Need a page - create a file
  • You need a set of pages - create a file and connect a component there that works with infoblocks
  • You need to set a title for the page - edit the file
  • You need to set a title for all pages of the section - create a special .section.php file in the root of this section
  • You need to edit the rights - edit the .access.php file
  • Settings before system initialization - in dbconn.php, .settings.php and .settings_extra.php files
  • result_modifier.php, component_epilog.php, init.php, .parameters.php, .description.php ....

And there are a lot of such special files scattered around Bitrix. On the one hand, this gives a certain flexibility when working with the system. On the other hand, it can turn into a torment for both the developer and the site manager. Page files sometimes turn into a mess of php code, layout, and plug-ins. As a result visual editor may incorrectly parse this file, and when editing it, it can easily escape php tags in some places, which will lead to the page not working. You say - do not write php code in such files? Yes I know. But Bitrix very often and without alternative forces to do so.
Yes, and you need to keep in mind constantly information about what kind of files they are, and what data they may contain. AT different files should contain different data different structure, and you need to remember it for each option. Looking for it in the documentation every time is hard work.

In addition to the above

You can endlessly complain about how badly everything is arranged in Bitrix. In my opinion, all these complaints can be characterized by one phrase - "somehow not completely." And indeed, if Bitrixoids suddenly announce some kind of feature, then they somehow do not release it completely, do not finish it, do not bring it to mind. Examples - mass:

  • implemented ORM - not completed, you can not use it to the fullest
  • made an autoloader, it only works in modules, and not by standards
  • made it possible to connect a template engine, but it can not be used everywhere, and not completely
  • etc. etc.

In a nutshell, I will try to characterize the rest of the problems that I have to face on a daily basis.

admin

If someone worked with the admin panel, created their pages in the administrative part in the way that Bitrix suggests doing, they will understand me. It's just hell. For those who are not in the know, Bitrix suggests using a file with noodles for each page. For example, the order detail view page in the admin area by Bitrix developers takes over 4k lines. My IDE starts to slow down when viewing the contents of this file. There you have php, js, and html. Well, at least they got rid of SQL, although I'm sure that it is on other administrative pages.
And what prevented the administrative pages from doing the work using the same components is not clear. There is simply no way to customize most of the administrative pages. In the case of components, this could be done in a jiffy.
By the way, kind people made a module that will help you build administrative pages

js framework

Bitrix has a js component that acts as a kind of client framework. None of the developers like it for several reasons:
  • it is almost undocumented
  • he is monster
  • it largely duplicates jquery familiar to many

Bitrix very often uses it in its components, thereby causing even more anger among developers. The core of this library in a minified form is 85kb, which is not a lot. It will not be possible to avoid its connection if you want to use all the features of Bitrix (composite, asset-management).

copy-paste spirit

AT recent times less and less, but still quite often, Bitrix makes something copy-paste. If you want to modify the work of a component - copy-paste. If you want to create your own upload template, copy-paste the system one and finish it. If you want to make almost the same template that you have - copy-paste and change it a little. And they even talk about it in courses for novice developers. I have no words.

Asset management and CDN

I really like the way of resource management in Bitrix. In principle, it is possible to register a set of certain "libraries". Each library is a set of css/js files that may depend on some other libraries. If you include some library on the page, then before connecting it, all dependencies will be resolved and all dependent libraries will be inserted on the page. Everything seems to be fine, only each resource will be inserted in the form separate file in a script or link tag. And thanks to this, there are sites that have 30-50 scripts connected and the same number of style files.
Shit-question, they said in Bitrix, and made a magic checkmark that combines all these files into one. And sites appeared where instead of 50 scripts there were 2, each 300-500kb. Some time ago, this union worked with errors and combined the same resources several times, but now it seems to have been fixed.
And then the Bitrixoids got out - they screwed up the ability to upload all resources to the CDN server. Which always falls off...
Then Google Pagespeed Insights appeared, which recommended lowering all resources in lower part pages. And in Bitrix again they made a magic checkmark, which stupidly lowers all resources in the body, if they are not marked with a special attribute.
They also distribute minified versions of their scripts along with the box, which are connected when using another magic checkmark in the admin panel.
In general, no scss for you, no TypeScript. If you want to competently manage resources - do not use the built-in Bitrix system, use webpack, which you can easily make friends with Bitrix.

Multisite / multilingual

This is probably the biggest developer headache that has been going on since the inception of the product. You can't just take it and create a multilingual site. And if you need a multilingual catalog with different prices and currencies - then it turns into flour, for which you also need to pay a tidy sum (you will have to fork out for the purchase of an additional license for the next language version of the site).
If you are creating a multilingual and multicurrency site, then be prepared for the fact that Bitrix will resist this very aggressively. Multisite settings are decentralized throughout the admin panel. Each entity in the admin panel has its own dependence on the language version of the site. Some entities may not support site / language dependencies at all, and some have only an unambiguous binding to the language, so this entity will have to be duplicated and then supported.
AT basic version to make an infoblock work in several languages, you will have to create a duplicate of this infoblock. But in practice, no one does this, and tries to come up with their own ways of storing one entity centrally, spreading its language-dependent attributes to other stores.
You cannot set the default language when localizing. If you have a language variable that describes a phrase in Russian, and this language variable is not available in English, then the English site will show empty line, and this cannot be influenced in any way (in many cases, one could leave the Russian phrase so that there are no voids).

Rights management mechanism

Very zamudili with this subsystem. It is often difficult to figure out why you granted the rights to view some entity, and the user cannot use them. For example, to give the right to edit an infoblock, you need to give access to the /bitrix/admin directory, grant permissions for a specific infoblock, and give permissions in the main module. Too many operations need to be done to issue rights for one entity. And if there are not enough rights, then without picking in the source codes it will not be possible to understand why.

Configuration

Bitrix does not have a centralized hub that would allow you to manage system settings. Settings are again decentralized throughout the system. There are options in the module settings, in the component settings, in COption (without being placed in the admin panel). In the admin panel, the options of one module can be spaced 3-4 meters apart different pages which are located in completely different places. urlrewrite can be edited through the admin panel! Now also .settings and .settings_extra. Sometimes it is not at all clear which of them have more priority, very often there are not enough explanations for the options, the relationships are not clear. There is no native way to share configuration between developers.
The settings are very illogical. Sometimes it comes to the point of absurdity ... look at the bigdata component - can an unprepared person be able to set it up?

Integration with 1C

This is the item on the list of Bitrix features that is enough to bite a large number of customers. Bitrix promises to set up two-way integration of the site with 1C in 2 clicks, which will instantly deliver content and documents from one system to another.
Yes, it really is, but with a few caveats.
Firstly, in order to make the integration “out of the box” without additional efforts, you need to do everything exactly as it is written in the Bitrix documentation - build a catalog on the site according to the rules that Bitrix offers and build a catalog in 1C that Bitrix requires. Ideally, create everything from scratch, and then maybe everything will work for you out of the box.
Secondly, Bitrix is ​​not friendly with all 1C configurations out of the box. Worth checking out first
Thirdly, ideal world can not be. Usually, a customer who wants a website already has a retail business, which means they already have 1C, which is a huge trash can. And this garbage has to be thrown onto the site. And so that the site does not get the same trash, it is necessary to significantly improve the exchange mechanism.
Very often, the customer's requirements differ greatly from the vision of the product that was formed by the Bitrix team, and then the modification of the exchange mechanism can be quite expensive, in terms of labor intensity comparable to the development of a unique exchange module for a specific case.
Therefore, there is no need to be under illusions about the fact that you will be able to easily integrate the site with 1C. These are all the machinations of marketers.

Refinement of the exchange with 1C is also a separate issue. The \CIBlockCMLImport class is responsible for organizing the catalog exchange. - 5.7k lines. One of the main methods that most often needs to be extended is \CIBlockCMLImport::ImportElement, which contains more than 1k lines. It is enough to inherit it once, update the product a couple of times for a long time, and you can get a non-working exchange with 1C. Therefore, developers often do not climb into this class and try to somehow get into the import process using event handlers. Working with event handlers in Bitrix, especially in the infoblock module, is also not a very pleasant experience, if only because events of the same type are not arranged uniformly, and some events are simply not enough.
In general, things are just as sad with this as before.

Inconsistency

Sometimes it seems to me that the developers different modules they don't really communicate with each other. Studying the source code of the kernel, you come across very heterogeneous solutions that could be implemented on one engine, but for some reason they are implemented differently.
For example, we can take the properties of infoblock elements and UserFields. Both of these entities are, in fact, additional field for another entity. It has a type, a value, and a description. The value is stored in a separate table(s) of the database, they have approximately the same data access interface. So why not make them the same interface?
At the end of March, the sale module was updated to latest version, and they also promised custom properties for orders. Is there now a new, third interface for working with extended entity properties?

Bitrix24

This is generally a separate topic for discussion. There is often confusion over this system. There are 2 versions of B24 - SaaS and Standlone. There is a marketplace for B24, but it contains applications only for the SaaS version! If you have a boxed version purchased for 200 pieces, you will not be able to put this top apps, as a document constructor, and in general, you will not be able to install any application from the marketplace for Bitrix24 on your Bitrix24. Here is such a paradox.
Instead, a marketplace from regular version. There are many more solutions out there, but they are mostly centered around Site Management, not B24.

Bitrix24, as I was told in the department technical support, it is a complete system. If you interfere with work standard components system, then be prepared that this functionality will break with subsequent updates. Bitrix will not count on you finalizing the portal components, and this is despite the fact that they officially send their clients to partners

By the way, modify the components in boxed version B24 is another problem. Components that generate js code that accesses via ajax php code, which generates html+js in response. It's a hell of a mixture that you really don't want to dive into.

Documentation

Bitrix documentation lags behind product development by 1-1.5 years. The code is very poorly covered by phpDocs, and often the comment before the class is just for show, being automatically generated in the IDE.
The very style of presentation of documentation in official sources is often too “free”, and the content of some articles in the documentation may have nothing to do with Bitrix itself.
The developer course has a lot of information, but the format in which the developer is introduced to the capabilities of the system does not provide the level of understanding that is required. If you go to the Symfony Cookbook, then everything is sorted out there, all the necessary aspects are described depending on the version. Whereas in Bitrix, the developer's training course contains incomprehensibly by what principle structured information according to the old and new core, which is served first separately, and then mixed, from which beginners have a headache.

Organization of the development process

Due to the specificity of the system, it is not so easy to organize convenient process development. Not the most fresh version Edition Business (what was at hand) after installation takes, think about it, almost 530 megabytes
$ du -s *|sort -nr|cut -f 2-|while read a;do du -hs $a;done 523M bitrix 204K upload 64K bitrixsetup.php 56K desktop_app 20K readme.html 20K license.html 4.0K web .config 4.0K urlrewrite.php 4.0K readme.php 4.0K license.php 4.0K install.config 4.0K index.php
Of this volume, a good half are binaries and installers, which, in general, are not needed for version control. Generally speaking, it is customary not to version the Bitrix kernel. Bitrix developers, as it were, guarantee the integrity of the kernel themselves, manage the dependencies of the versions of different modules during updates. But this immediately carries at least one big minus - it is impossible to deploy a fully working project with one command from version control, you have to build it in parts: get the kernel sources from the bitrix backup, and the developers' sources from git.
The base is not good either. If you yourself can use migrations during development, then Bitrix rolls updates into the database using ordinary scripts that you cannot control. Therefore, when updating, you still have to transfer database backups from the central development host to other developers.
Kind people, again, are sawing tools that help to organize it all, but unfortunately, it is still not possible to force Bitrix to follow these rules.
Officially, Bitrix allows you to have 2 copies of one distribution. One is for production and the other is for development. If you have several developers on one project, then you are, as it were, outlawed) In fact, it is enough to cut off incoming and outgoing connections from/to www.bitrixsoft.com to the Bitrix machine, and then you can rivet as many copies of the development as you like, they just can't update themselves.

Colleagues

And the last question I would like to touch on.
Due to the fact that Bitrix has a low entry threshold, there are a lot of unskilled personnel among the companies that provide services in this market. I had a chance to see many different projects during my career (more than a hundred in total) completed on 1C-Bitrix. I can say with confidence that 95% of them were done "bluff". It was very rare that there were projects for the development of which an approach was felt, but these were few. This is all very sad.

findings

Of course, all the minuses cannot be considered within the framework of one article. Every day you come across some little things that interfere with work every day. But to consider all such trifles is simply impossible, and probably useless.

What conclusions can be drawn here. Bitrix is ​​an extremely complex system due to the fact that it has an ill-conceived architecture, many flaws that continue to live in the product for a long time. On the other hand, Bitrix is ​​enough simple system, which requires a much lower skill level to get started, unlike frameworks.
Support for this product is a very thankless task, compared to such products as Symfony, Laravel, Yii. The product is very fond of putting spokes in the wheels of both inexperienced and experienced developers, which, in turn, can affect the cost of services of experienced developers for Bitrix.

Do I regret spending so much time working with this system? Rather yes than no. It would be wiser to spend this time studying something more correct and more logical (which I am actively trying to do now). But it just so happened that there was no one to direct me in the right direction at the beginning of my journey.

If you - php beginner developer, then prefer Bitrix to study frameworks such as Symfony, Laravel, Yii, ZendFramework. Believe me, in the future it will more than pay off. Having mastered any of these frameworks, it will not be difficult for you to develop something for Bitrix in the future. If you have no choice, then study Bitrix, but in free time it’s better to try to plunge into the world of frameworks to put your brains in place.

If you are a developer with experience in Bitrix, but without experience in other frameworks, then be sure to plunge into another world, you will discover a lot of new and useful knowledge that will help you write much better solutions for 1C-Bitrix. Try to use solutions from other frameworks in your projects, since this is not difficult to do thanks to the component approach of the latter and composer.

If you are a customer, then do not trust Bitrix marketers. Nothing will be as easy as they say in Bitrix presentations. And do not blame your developers for this, they have nothing to do with it. If you want to create a large and complex online store of the Eldorado/mvideo/sportmaster level, then Bitrix may not be the best choice.

UPD. It can be seen that the Bitrix employees read the article. In the section about Marketing, I wrote that in the section Architecture in the course of the Bitrix developer, marketing calls were written. Now they are not there. They even sealed it, apparently in a hurry.

Thanks to nook for being observant and keen eye :)

Tags:

Add tags

No matter how much we use PHP, some features still pop up that we have not even heard of. Some of them would be very useful to us. I created a small list useful features, which should be in the arsenal of every PHP programmer.

1. Creating functions with a variable number of arguments

You probably already know that PHP allows us to create functions with optional arguments. Now I will show a function in which the number of arguments can change from case to case.

But first, let's remember how we create functions in the usual way:

// function with two optional parameters function foo($arg1 = "", $arg2 = "") ( echo "arg1: $arg1\n"; echo "arg2: $arg2\n"; ) foo("hello", "world"); /* output: arg1: hello arg2: world */ foo(); /* output: arg1: arg2: */

Now let's look at how you can write a function with an unlimited number of arguments. For this, the func_get_args() method will be used:

// do not specify arguments function foo() ( // returns an array of passed arguments $args = func_get_args(); foreach ($args as $k => $v) ( echo "arg".($k+1)." : $v\n"; ) ) foo(); /* output nothing */ foo("hello"); /* output arg1: hello */ foo("hello", "world", "again"); /* output arg1: hello arg2: world arg3: again */

2. Use Glob() to Find Files

Often the function names speak for themselves. The same cannot be said for the glob() function.

Without going into details, its functionality is similar to the scandir() method. It allows you to find required file by template:

// find all php files $files = glob("*.php"); print_r($files); /* output: Array ( => phptest.php => pi.php => post_output.php => test.php) */

To find files of several types, you need to write like this:

// find all php and txt files $files = glob("*.(php,txt)", GLOB_BRACE); print_r($files); /* output: Array ( => phptest.php => pi.php => post_output.php => test.php => log.txt => test.txt) */

You can also specify the path in the template:

$files = glob("../images/a*.jpg"); print_r($files); /* output: Array ( => ../images/apple.jpg => ../images/art.jpg) */

To get the full path to a document, use the realpath() method:

$files = glob("../images/a*.jpg"); // Apply the "realpath" function to each element of the array $files = array_map("realpath",$files); print_r($files); /* output: Array ( => C:\wamp\www\images\apple.jpg => C:\wamp\www\images\art.jpg) */

3. Information about the used memory

If you keep track of the amount of memory that is eaten up by your scripts, then you will probably optimize them more often.

In PHP there is powerful tool memory usage tracking. AT different parts load script may be different. To get the value of memory used in this moment, we should use the memory_get_usage() method. For fixation maximum number used memory use memory_get_peak_usage()

echo "Initial: ".memory_get_usage()." bytes \n"; /* Initial: 361400 bytes */ // give a small load for ($i = 0; $i< 100000; $i++) { $array = md5($i); } // и ещё for ($i = 0; $i < 100000; $i++) { unset($array[$i]); } echo "Final: ".memory_get_usage()." bytes \n"; /* Final: 885912 bytes */ echo "Peak: ".memory_get_peak_usage()." bytes \n"; /* Peak: 13687072 bytes */

4. Processor Information

To do this, you need to use the getrusage() method. But note that this feature will not work on Windows.

Print_r(getrusage()); /* prints Array ( => 0 => 0 => 2 => 3 => 12692 => 764 => 3864 => 94 => 0 => 1 => 67 => 4 => 0 => 0 => 0 => 6269 => 0) */

The picture outlined above will be clear to those who have experience in system administration. For everyone else, we offer a decryption:

  • ru_oublock: number of block writes
  • ru_inblock: number of block reads
  • ru_msgsnd: number of sent messages
  • ru_msgrcv: number of received messages
  • en_maxrss: maximum size nonpageable set
  • ru_ixrss: total shared memory
  • ru_idrss: total amount of unshared data
  • ru_minflt: number of memory pages used
  • ru_majflt: number of page faults
  • ru_nsignals: number of received signals
  • ru_nvcsw: number of context switches by process
  • ru_nivcsw: number of forced context switches
  • ru_nswap: number of disk accesses during paging
  • ru_utime.tv_usec: working time in custom mode(microseconds)
  • ru_utime.tv_sec: time spent in user mode (seconds)
  • ru_stime.tv_usec: privileged mode time (microseconds)
  • ru_stime.tv_sec: privileged mode time (seconds)

In order to find out what resources of your processor are used by the script, you need the value of 'user time' (time in user mode) and 'system time' (time in privileged mode). You can get the result in both seconds and microseconds. In order to convert the total number of seconds into decimal number, you need to divide the microseconds value by 1 million and add seconds to the value.

Somehow confusing. Here is an example:

// rest 3 seconds sleep(3); $data = getrusage(); echo "User time: ". ($data["ru_utime.tv_sec"] + $data["ru_utime.tv_usec"] / 1000000); echo "System time: ". ($data["ru_stime.tv_sec"] + $data["ru_stime.tv_usec"] / 1000000); /* prints User time: 0.011552 System time: 0 */

Although the script took about 3 seconds to complete, the processor was not heavily loaded. The matter is that at a call (sleep) the script practically does not consume resources of the processor. In general, there are many tasks that take a significant amount of time, but do not use the processor. For example, waiting for disk-related operations. So you don't always use CPU time in your scripts.

Here's another example:

// walk 10 million times for($i=0;$i<10000000;$i++) { } $data = getrusage(); echo "User time: ". ($data["ru_utime.tv_sec"] + $data["ru_utime.tv_usec"] / 1000000); echo "System time: ". ($data["ru_stime.tv_sec"] + $data["ru_stime.tv_usec"] / 1000000); /* выводит User time: 1.424592 System time: 0.004204 */

The script took 1.4 seconds of CPU time. In this case, system call times are generally low.

The privileged mode time (System Time) is the time that the processor spends executing system requests to the kernel on behalf of the program. Example:

$start = microtime(true); // call microtime every 3 seconds while(microtime(true) - $start< 3) { } $data = getrusage(); echo "User time: ". ($data["ru_utime.tv_sec"] + $data["ru_utime.tv_usec"] / 1000000); echo "System time: ". ($data["ru_stime.tv_sec"] + $data["ru_stime.tv_usec"] / 1000000); /* выводит User time: 1.088171 System time: 1.675315 */

Now the system time has been spent much more than in the previous example. All thanks to the microtime () method, which uses system resources.

However, it should be noted that the displayed time may not be accurate, because. at a given time, processor resources are also being used by other programs, which may result in a small error.

5. Magic constants

There are many magic constants in PHP such as current line number (__LINE__), file path (__FILE__), directory path (__DIR__), function name (__FUNCTION__), class name (__CLASS__), method name (__METHOD__) and namespaces (__NAMESPACE__).

We will not consider them all. Let's just look at a couple:

// this script depends on the current location of the file and // can cause problems if used from different directories require_once("config/database.php"); // this script won't cause problems require_once(dirname(__FILE__) . "/config/database.php");

Use __LINE__ when debugging scripts:

// code // ... my_debug("some debug message", __LINE__); /* output Line 4: some debug message */ // more code // ... my_debug("another debug message", __LINE__); /* output Line 11: another debug message */ function my_debug($msg, $line) ( echo "Line $line: $msg\n"; )

6. Generation of unique IDs

There are times when you need to generate a unique string. Many times I have seen that md5() function is used to solve this problem:

// generate a random string echo md5(time() . mt_rand(1,1000000));

But in fact, PHP has a special uniqid() function for this purpose.

// generate a random string echo uniqid(); /* outputs 4bd67c947233e */ // one more time echo uniqid(); /* prints 4bd67c9472340 */

With the naked eye, you can see that the first characters are similar to say the least ... This is due to the fact that this method uses server time to generate characters. It's even useful, because. all generated values ​​are obtained in alphabetical order, which makes it possible to quickly sort them.

In order to reduce the chances of getting a duplicate, we can add a prefix or use a second parameter (increase the number of characters):

// prefixed with echo uniqid("foo_"); /* output foo_4bd67d6cd8b8f */ // with second parameter echo uniqid("",true); /* outputs 4bd67d6cd8b926.12135106 */ // both echo uniqid("bar_",true); /* prints bar_4bd67da367b650.43684647 */

This method generates lines smaller than md5, so you can save space.

7. Serialization

Have you ever had to store complex data in a database or file? In order to convert an object to a string, PHP provides a special function.

Generally speaking, these methods are 2: serialize() and unserialize()

// complex array $myvar = array("hello", 42, array(1,"two"), "apple"); // convert to string $string = serialize($myvar); echo $string; /* output a:4:(i:0;s:5:"hello";i:1;i:42;i:2;a:2:(i:0;i:1;i:1;s :3:"two";)i:3;s:5:"apple";) */ // get the original value $newvar = unserialize($string); print_r($newvar); /* prints Array ( => hello => 42 => Array ( => 1 => two) => apple) */

This is how these functions work. However, due to the rapid growth in popularity of JSON, 2 methods json_encode() and json_decode() were added in PHP 5.2. Their work is similar to serialize():

// complex array $myvar = array("hello", 42, array(1,"two"), "apple"); // convert to string $string = json_encode($myvar); echo $string; /* prints ["hello",42,,"apple"] */ // restore the original value $newvar = json_decode($string); print_r($newvar); /* prints Array ( => hello => 42 => Array ( => 1 => two) => apple) */

This option is more compact and compatible with other languages ​​such as JavaScript. However, when working with very sophisticated objects, data loss can occur.

8. String Compression

When we talk about compression, then immediately come to mind archive files in ZIP format. PHP provides the ability to compress long strings without any files.

AT following example Let's demonstrate how the gzcompress() and gzuncompress() functions work:

$string = "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nunc ut elit id mi ultricies adipiscing. Nulla facilisi. Praesent pulvinar, sapien vel feugiat vestibulum, nulla dui pretium orci, non ultricies elit lacus quis ante. Lorem ipsum dolor sit amet , consectetur adipiscing elit. Aliquam pretium ullamcorper urna quis iaculis. Etiam ac massa sed turpis tempor luctus. Curabitur sed nibh eu elit mollis congue. Praesent ipsum diam, consectetur vitae ornare a, aliquam a nunc. In id magna pellentesque tellpis posuere seded non mi metus, at lacinia augue. Sed magna nisi, ornare in mollis in, mollis sed nunc. Etiam at justo in leo congue mollis. Nullam in neque eget metus hendrerit scelerisque eu non enim. Ut malesuada lacus eu nulla bibendum id euismod urna sodales . "; $compressed = gzcompress($string); echo "Original size: ". strlen($string)."\n"; /* prints Original size: 800 */ echo "Compressed size: ". strlen($compressed)."\n"; /* output Compressed size: 418 */ // return $original = gzuncompress($compressed);

We can reduce the amount of text by 50%. For the same purpose, you can use the gzencode() and gzdecode() methods, which use a different compression algorithm.

9. Run before completion

PHP has a register_shutdown_function() function that will allow you to execute some code before the script terminates.

Let's say you want to find out some information... Script running time:

// get start time $start_time = microtime(true); // some operations // ... // print the running time echo "execution took: ". (microtime(true) - $start_time). "seconds.";

At first glance, this may seem like a trivial task. For these purposes, you can put the code at the end of the file. However, if the exit() function is executed somewhere before, this code will never work. Also, it will not work if there is an error on the page or the user interrupts the page loading (by clicking on the appropriate button in his browser);

When using the register_shutdown_function() method, the code will be executed anyway:

$start_time = microtime(true); register_shutdown_function("my_shutdown"); function my_shutdown() ( global $start_time; echo "execution took: ". (microtime(true) - $start_time). " seconds."; )

Conclusion

PHP is a whole planet that never ceases to amaze us with its content. What do you think of these features?

Top Related Articles