Chatty section php. Bitrix - How to build navigation for sections and subsections


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

1. Creating functions with a variable number of arguments

Most likely, you 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 vary 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"); /* will output: arg1: hello arg2: world */ foo(); /* will output: arg1: arg2: */

Now let's look at how you can write a function with an unlimited number of arguments. To do 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(); /* will not output anything */ foo("hello"); /* will print arg1: hello */ foo("hello", "world", "again"); /* will print arg1: hello arg2: world arg3: again */

2. Use Glob() to search for files

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

Without going into too much detail, its functionality is similar to the scandir() method. It allows you to find the required file using a template:

// find all php files $files = glob("*.php"); print_r($files); /* will 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 array element $files = array_map("realpath",$files); print_r($files); /* will output: Array ( => C:\wamp\www\images\apple.jpg => C:\wamp\www\images\art.jpg) */

3. Information about memory used

If you keep track of the amount of memory consumed by your scripts, you will probably optimize them more often.

PHP has a powerful memory tracking tool. The loads may be different in different parts of the script. To get the currently used memory value, we should use the memory_get_usage() method. To fix the maximum amount of memory used, 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 keep in mind 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 transcript:

  • ru_oublock: number of block write operations
  • ru_inblock: number of block read operations
  • ru_msgsnd: number of messages sent
  • ru_msgrcv: number of received messages
  • ru_maxrss: maximum size of a non-paged set
  • ru_ixrss: total amount of shared memory
  • ru_idrss: total volume of unshared data
  • ru_minflt: number of memory pages used
  • ru_majflt: number of page missing errors
  • ru_nsignals: number of received signals
  • ru_nvcsw: number of context switches by the process
  • ru_nivcsw: number of forced context switches
  • ru_nswap: number of disk accesses when paging
  • ru_utime.tv_usec: operating time in user mode (microseconds)
  • ru_utime.tv_sec: operating time in user mode (seconds)
  • ru_stime.tv_usec: operating time in privileged mode (microseconds)
  • ru_stime.tv_sec: operating time in privileged mode (seconds)

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

It's kind of confusing. Here's an example:

// rest for 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 execute, the processor was not heavily loaded. The fact is that when called (sleep), the script consumes virtually no processor resources. 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.

Privileged mode time (System Time) is the time 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 slight error.

5. Magic constants

There are many magic constants in PHP, such as the 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 look at just a couple:

// this script depends on the current file location and // may cause problems if used from different directories require_once("config/database.php"); // this script will not cause problems require_once(dirname(__FILE__) . "/config/database.php");

Use __LINE__ when debugging scripts:

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

6. Generating unique IDs

There are times when you need to generate a unique string. I have seen many times that the 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 function uniqid() for these purposes

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

With the naked eye you can see that the first symbols are, to put it mildly, similar... This is due to the fact that this method uses server time to generate symbols. This is 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 (increases the number of characters):

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

This method generates strings smaller than md5, thereby saving space.

7. Serialization

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

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

// complex array $myvar = array("hello", 42, array(1,"two"), "apple"); // convert to string $string = serialize($myvar); echo $string; /* will print 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); /* will output 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 to 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; /* will print ["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 complex objects, data loss may occur.

8. String compression

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

The following example demonstrates 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 tellus posuere ad ipiscing.Sed 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"; /* will output Original size: 800 */ echo "Compressed size: ". strlen($compressed)."\n"; /* will output Compressed size: 418 */ // return $original = gzuncompress($compressed);

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

9. Execute before exiting

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

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

// get the start time $start_time = microtime(true); // some operations // ... // display 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 place the code at the end of the file. However, if the exit() function fires somewhere before this, 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 corresponding button in his browser);

When using the register_shutdown_function() method, the code will be executed in any case:

$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 about these functions?

This material is a free translation of the article:
Ire Aderinokun SECTIONING CONTENT IN HTML5 - DIV OR SECTION OR ARTICLE?

HTML5 has become an important stepping stone for the concept of semantic code. He advocates that a document should be structured and the tags you use should convey meaning.

Among other things, tags

And
were introduced to make content areas more meaningful than just
. But in what case should we use these new elements and when the usual
preferable?

Element overview

DIV

Element

is a general purpose element. But that doesn't make much sense. Its purpose is to group content that is not semantically related. In fact, this is completely meaningless for screen readers, so you need to use this method with caution.

Element

Mainly used for content grouping and positioning using CSS. For example, as a container for other elements.

SECTION

Element

is a little more specific than the element
. It applies to a general section of content that can be grouped semantically.

The main rule is that the section element is only appropriate when its contents can be explicitly grouped.

Because the content of the tag

only makes sense when grouped together, it must have a "theme". The "topic" should be defined by including a title within the content, often immediately after the opening tag.

Subscribe to the Newsletter


ARTICLE

Tag

is even more specific than the tag
. It also applies to a semantically related section of content and must have a title. However, its content must be self-contained. This means that when isolated from the rest of the page it should still make sense.

Tag purpose

in content tagging, such as blog markup.


Article Title



Quae similitudo in genere etiam humano apparet. Est, ut dicis, inquam...


DIV or SECTION or ARTICLE?

So which tag should you use when?

If the content is not semantically related, you should use

. If semantically related content can stand alone, then use the tag
. Otherwise use
.

Combining elements

Let's try to combine the various elements together.

Article in article

Article elements can be nested inside each other. And although they are still self-sufficient, it is assumed that the contents of the internal

connected with the external.

Article Title

John Smith

Lorem ipsum dolor sit amet, consectetur adipiscing elit.

Another Article

Jane Doe

Lorem ipsum dolor sit amet, consectetur adipiscing elit.

Lorem ipsum dolor sit amet, consectetur adipiscing elit.


Article in section

We can also add several tags

place inside
. A good example would be a blog page that displays the latest posts. The container for all recent posts will be a tag
, while each individual section of a recording can be marked with a tag
.

Latest Blog Posts

Blog Post Title

Lorem ipsum dolor sit amet, consectetur adipiscing elit.

Blog Post Title

Lorem ipsum dolor sit amet, consectetur adipiscing elit.


Section in article

Each individual tag

may contain a section section. For example, this post could be marked up like this:


Sectioning Content in HTML5 - div or section or article?


Overview of the Elements



div


The div element is the most general purpose element.




From this article you will learn how to build a breadcrumb chain knowing only the symbolic code of the section.

How to build breadcrumbs using the symbolic code of a section in Bitrix

Before reading this article, I advise you to read How to add a title to breadcrumbs. Have you read it? Then let's move on.

In older components, there were cases where only the symbolic code of a section was stored in the array. This variable was called .

If the symbolic codes of sections on your site are unique (which is always recommended to be set in the infoblock settings), then there will be no problems. First, find the file section.php your component.

$rsSect = CIBlockSection::GetList(array(), array("IBLOCK_ID" => $arParams["IBLOCK_ID"], "=CODE" => $arResult["VARIABLES"]["SECTION_CODE"]), false, array ("ID", "NAME", "UF_TEXT_TOP", "DEPTH_LEVEL", "SECTION_PAGE_URL")); if ($arSect = $rsSect->GetNext()) ( $SEC_LVL = $arSect["DEPTH_LEVEL"]; $SEC_NAME = $arSect["NAME"]; $SEC_URL = $arSect["SECTION_PAGE_URL"]; )

Pay attention to the line ‘=CODE’ => $arResult[‘VARIABLES’][‘SECTION_CODE’]. Also, we use if, instead of the usual while loop, because we only need data for one partition.

We write down 3 variables that we will need:
— level of nesting, DEPTH_LEVEL
- Name, NAME
- link to the section, SECTION_PAGE_URL

IMPORTANT. Before the next stage turn off in your component, the “add section\infoblock to the navigation chain” setting

At the very end of the section.php file, add the code:

= 2) ( $rsSect = CIBlockSection::GetList(array(), array("IBLOCK_ID" => $arParams["IBLOCK_ID"], "=CODE" => $arResult["VARIABLES"]["SECTION_CODE"]) , false, array("ID", "NAME", "SECTION_PAGE_URL")); while ($arSect2 = $rsSect->GetNext()) ( if (strstr($curSectionURL, $arSect2["SECTION_PAGE_URL"])) ( $SEC_NAME = $arSect2["NAME"]; $SEC_URL = $arSect2["SECTION_PAGE_URL"]; break; ) ) $result = array(); $ibsTreeResource = CIBlockSection::GetNavChain(false, $arSect2["ID"] , array("ID", "NAME")); $c = 0; while($sectionItem = $ibsTreeResource->Fetch())( $result[$c]["NAME"] = $sectionItem["NAME" ]; $res = CIBlockSection::GetByID($sectionItem["ID"]); if($ar_res = $res->GetNext()) ( $url = $ar_res["SECTION_PAGE_URL"]; ) $result[$c ]["URL"] = $url; $c++; ) foreach ($result as $arItem) ( $APPLICATION->AddChainItem($arItem["NAME"], $arItem["URL"]); ) ) else ( $APPLICATION->AddChainItem($SEC_NAME, $SEC_URL); ) ?>

With help CIBlockSection::GetNavChain build the full path to the parent section (if it is a subsection), and add it through a loop to the navigation chain Title and Link. If this is also a 1st level section, then simply add it Title and Link.

For example, our code is armstrong. The resulting result looks approximately like this:
Catalog / Office LED lights/ Armstrong lamps

The URL then looks like:

/catalog/ofisnye-svetilniki/armstrong/

The link to the Catalog is provided automatically.
Office LED lamps are the main section.
Armstrong lamps are the section we are in now. The breadcrumb component does not link to it.

That's all, I hope everything worked out for you :). The PS code is not perfect and was used for old projects, it can be improved.

Minimizing code duplication through better organization and reuse is an important goal of object-oriented programming. But in PHP Sometimes things get tricky - due to the limitations of the single inheritance model you use, you may have some methods that you would like to use across multiple classes, but they may not fit well into the inheritance hierarchy.

Languages ​​like C++ And Python, allow us to inherit from several classes, which to some extent solve this problem, and mixins in Ruby allows you to mix the functionality of one or more classes without using inheritance. But multiple inheritance has its problems.

In this article I will talk about traits in php- new functionality introduced in PHP 5.4 to solve such problems. The concept of traits themselves is not something new to programming and is used in other languages ​​such as Scala And Perl. They allow us to reuse code through independent classes in different hierarchies.

What does the trait represent?

A trait is like an abstract class that cannot be instantiated on its own (though it is more often compared to an interface). Documentation PHP defines traits as follows:

Traits are a mechanism for code reuse in individual languages ​​such as PHP. The trait is intended to overcome some of the limitations of single inheritance, allowing the developer to freely use multiple methods in multiple independent classes located in different hierarchies.

Let's look at an example:

Class DbReader extends Mysqli()

Class FileReader extends SplFileObject()

Everything will be fine until we need to use common functionality for these classes. Of course, we can write the same piece of code twice, but this is by no means a good practice.

Let's say both classes should be singletons. Because the PHP does not support multiple inheritance, each class will need to implement the necessary code to support Singleton template. Traits offer a solution to exactly this kind of problem.

Trait Singleton
{
private static $instance;

Public static function getInstance() (
if (!(self::$instance instanceof Singleton)) (
self::$instance = new self;
}
return self::$instance;
}
}

Class DbReader extends ArrayObject
{
use Singleton;
}

Class FileReader
{
use Singleton;
}

Trait Singleton contains implementation Singleton template with static method getInstance(), which creates a class object using this trait (if it is not already created) and returns it.

Let's try to create objects of these classes using the method getInstance().

$a = DbReader::getInstance();
$b = FileReader::getInstance();

Var_dump($a); //object(DbReader)
var_dump($b); //object(FileReader)

We can see that $a is an object DbReader, A $b is an object FileReader, but both now behave like template-implementing objects Singleton. Method from class Singleton was introduced into classes that use his trait.

Traits do not impose any additional semantics on the class. In some ways you can think of this as a level copy and paste mechanism PHP interpreter, where the methods of this trait are copied to the layout class.

If we just extend the class DbReader from parent with hidden property $instance, the property will not appear in the dump ReflectionClass::export().

Using Multiple Traits

So far we have only used one trait, but in some cases we may need to include the functionality of more than one trait in a class.

Trait Hello
{
function sayHello() (
echo "Hello";
}
}

Trait World
{
function sayWorld() (
echo "World";
}
}

Class MyWorld
{
use Hello, World;
}

$world = new MyWorld();
echo $world->sayHello() . " " . $world->sayWorld(); //Hello World

Here we have two traits: "Hello" and "Peace". Trait Hello can only say "Hello" and trait World can say "Peace". In class MyWorld we applied Hello And World to object MyWorld received methods from both traits and could say "Hello World".

In one of the following articles we will continue to discuss traits. And that's all for today. Thank you for your attention!







2024 gtavrl.ru.