Posts

Showing posts with the label PHP

Symfony - Twig - How to check on instanceof class object

In Twig exist "constant" function that returns constant value, but if you set "class" in first parameter and object in second parameter, then function returns the fully qualified class name of an object.  So we can use it in our case and compare it on class name that we want to check like "instanceof". Example: {% if constant('class', app.user) == 'User' %}{% endif %} Or with namespace: {% if constant('class', app.user) == 'EntityBundle\\Entity\\User' %}{% endif %}

Which PHP Framework to choose in 2024

 If you've decided to start learning a PHP framework this year, or from scratch, and can't decide which one to choose, here's a selection of the most popular: Laravel - 302,403,373 downloads Symfony - 78,291,128 downloads Cakephp - 12,444,302 downloads Codeigniter4 - 1,720,925 downloads Codeigniter - 1,617,412 downloads by downloads in January 2024 All info from Packagist.org So, to choose Laravel in this year, you obtain much more possibilities to find a job. 

Symfony - Doctrine - How to set one-to-one relation with field not exist in target table, but exist in another one

Today, I faced with a bug: Custom Field entity has a RelId column relates to two different entities: Product and Bundle. Set RelId into Custom Field directly connected to Product, but not exist in Bundle table. After Entity Manager flush(), I got an error: RelId can not be null. How come that RelId field became null, when flushing. After debugging, I realized, Doctrine checks if exist this connected RelId field in Bundle table. If not, Doctrine just set RelId to null and go on. So, we need not to set RelId directly, but using entity, like Product or Bundle, in my case. Here's a simplified example using annotations: Let's assume you have three entities: SourceEntity, TargetEntity, and RelationEntity. RelationEntity will act as the join table, holding the relationship between SourceEntity and TargetEntity. // SourceEntity.php use Doctrine\ORM\Mapping as ORM; /** * @ORM\Entity */ class SourceEntity { // ... other properties /** * @ORM\OneTo...

Symfony - Doctrine - How to change old attributes in entity to new PHP 8 attributes

Old-Style Annotations: Written as comments, typically using PHPDoc syntax (/** ... */). Annotations are interpreted by external tools or libraries. Doctrine ORM interprets annotations to configure database mappings. Limited flexibility in terms of syntax and available metadata types. May lack type safety and validation. PHP 8 Attributes: Written using the #[...] syntax. Introduced as a language feature in PHP 8 for adding metadata directly to code. Provides a more structured and standardized way of associating metadata with classes, methods, or properties. Attributes are a built-in language feature, eliminating the need for external interpretation in many cases. Attributes are directly handled by the PHP runtime. Offers better type safety and validation compared to traditional annotations. Supports the use of PHP's native types and expressions within attribute values. Attributes support namespacing, allowing for better organization and...

Symfony - Doctrine - How to add subquery into where clause

If you want to add subquery into where clause, you need to create subquery firstly: $sub = $this->_em->createQueryBuilder()             ->select('cf.id')             ->from(CustomField::class, 'cf')             ->where('cf.type = :type AND cf.fieldName = :fieldName'); After that you can use this subquery as DQL: $this->_em->createQueryBuilder()->expr()->in('cfv.fieldId', $sub->getDQL()) In that case we use it as IN condition. But it is just example. And finally it will look like that: $this->createQueryBuilder('cfv')             ->update(CustomFieldValue::class, 'cfv')             ->set('cfv.value', ':value')             ->where($this->_em->createQueryBuilder()->expr()->in('cfv.fieldId', $sub->getDQL()))           ...

WordPress - How to create simple plugin with shortcode

Creating a simple WordPress plugin involves a few steps. Below is an example of a minimalistic WordPress plugin that adds a custom shortcode to display a greeting message. Step 1: Set Up Plugin Structure Create a new folder for your plugin in the "wp-content/plugins" directory. Let's call it "simple-greeting-plugin". Step 2: Create the Main Plugin File Inside your plugin folder (simple-greeting-plugin), create a main PHP file, e.g., "simple-greeting-plugin.php". Step 3: Add Plugin Information In your main PHP file, add the plugin information in the comment header. <?php /* Plugin Name: Simple Greeting Plugin Description: A simple WordPress plugin that adds a greeting shortcode. Version: 1.0 Author: Your Name */ Step 4: Add Greeting Shortcode Functionality Now, let's add the functionality to display a greeting message using a shortcode. Update your "simple-greeting-plugin.php" file as follows: <?php /* Plugin Name:...

Symfony - How to fix Circular Reference

 A circular reference in Symfony typically occurs when there's a loop in the dependency injection graph. It means that one service depends on another service, which in turn depends on the first one, creating an infinite loop. Check Your Service Definitions: Review your service definitions in the services.yaml or other configuration files. Look for any circular dependencies. A circular reference often occurs when Service A depends on Service B, and Service B depends on Service A. Use Setter Injection: Instead of injecting dependencies through the constructor, use setter injection. In Symfony, you can use setter injection by creating setter methods in your services and injecting dependencies through these methods after the service is instantiated. Lazy Loading: Consider using lazy loading for dependencies. Symfony allows lazy loading of services, which means that the actual instantiation of a service is delayed until it's actually used. You can enable lazy loading for a service b...

PHP - How to show expected return array elements

When your function or method returns an associative array, it's beneficial to document the expected structure of that array using PHPDoc type annotations. This practice not only serves as documentation for developers using your code but also enables features like auto-completion in integrated development environments (IDEs). For example: /** * Creates a user. * * @return array{"name": string, "age": int, "married": bool} */ function createUser(): array { return ['name' => 'Nayf', 'age' => 38, 'married' => true]; } In this PHPDoc block, the @return annotation is used to specify that the function returns an associative array with three elements: "name" of type string, "age" of type int, and "married" of type bool. This information provides clarity on the expected structure of the returned array. The PHPDoc type system supports various basic PHP types such as string, bool, in...

Symfony - How to generate URL without controller or path

If you need to generate URL out of controller, you need to create you own Route with necessary path. $route = new \Symfony\Component\Routing\Route('/calculator/new'); And add this route to Route Collection: $routes = new \Symfony\Component\Routing\RouteCollection(); $routes->add('calculator_new', $route); After that you can generate URL: $generator = new \Symfony\Component\Routing\Generator\UrlGenerator($routes, new \Symfony\Component\Routing\RequestContext()); $url = $generator->generate('calculator_new'); This returns: "/calculator/new" If you need to add any query parameters: $url = $generator->generate('calculator_new', ['width' => 100]); This will return "/calculator/new?width=100" as the generated URL, including the specified query parameter. In summary, by creating a route, adding it to a collection, and using a URL generator, you can easily generate URLs and include additional query parameters...

PHP - How to explode empty string with empty array

When you try to explode empty string, you get not empty array, as we would have assumption, but array with one element with blank string. PHP says it is not a bug. So, we need to find a way how to avoid this behavior. As we don`t want to have any element in array after exploding empty string. We want to have empty array as well, obviously. We can use "array_filter" function to remove empty element in array. Example: $correctArray = array_filter(explode(';', ''));

Wordpress - REST API - How to set up roles

Wordpress REST API allows roles as array. But when you try to set roles as it is, it throws error. Correct list of roles: administrator editor author contributor subscriber customer As you see, all of these role names must be in lower case . For example: $user = WordpressAPI::createUser([ 'username' => 'test', 'email' => 'test@gmail.com', 'password' => '123456QQQ', 'roles' => ['subscriber'] ]); And you can add your own roles that you created in system.

Wordpress - How to log errors

On the first glance, it is easy to answer on this question. But, it is not. Yes, you can simply set WP_DEBUG constant to true, as many sites recommend. But, probably, it comes more problems than convenience. Because, it throws out all unnecessary, for your case, messages on the site, and, most likely, just fall apart whole layout. So, I recommend, do not switch on WP_DEBUG constant, and log what you want silently from users. For that: Set WP_DEBUG constant to true. We need to set up WP_DEBUG_DISPLAY constant to false, to hide errors from users. Write where you need error_log(). After that, you can check your logs and see error messages. If not, try to set up WP_DEBUG_LOG constant. There should be path to log file. wp-config.php file: define( 'WP_DEBUG', true ); define( 'WP_DEBUG_DISPLAY', false ); define( 'WP_DEBUG_LOG', '/path/to/log/file.txt' ); // if needed

Symfony - How to logout locked or banned User automatically

If you want to logout locked or banned User automatically, you need, first of all, add new Listener with onKernelRequest(RequestEvent $event) method. Just FYI, this method Symfony calls every time on every request, so, be careful to use this method. It can shoot yourself in the foot. For example: class SecurityUserListener { public function onKernelRequest(RequestEvent $event) { } } After that, we need to check our User on status: banned or locked (what you need). For this we need to inject Token Storage in class constructor. Token Storage can return User. So, lets do it: class SecurityUserListener { public function __construct(private TokenStorageInterface $tokenStorage) { } public function onKernelRequest(RequestEvent $event) { $user = $this->tokenStorage->getToken()?->getUser(); } } Now, you can examine the user object's status. If it meets your criteria, set the current token to null (indicating no user in the token anymore) and...

Symfony - How to make Facade Service

A Facade Service is employed to obtain any service through a public static method, as opposed to injecting it via the constructor. For example (facade service): Facade::getEntityManager(); In this example, the getEntityManager method is accessed directly from the Facade, providing a simplified and centralized way to obtain the EntityManager service. For example (injecting service): class test { public function __construct(private EntityManagerInterface $em) {} } In this case, the EntityManager service is injected into the constructor of the Test class. While this is a valid approach, Facade Services offer an alternative method for obtaining services. To add creating facade possibility, first of all, need to set Service Container to Bundle boot() method. For example: class CoreBundle extends Bundle { private static $serviceContainer; public function boot() { parent::boot(); self::$serviceContainer = $this->container; } } Now, we have Se...

is_null() или === null ???

Всем привет! я тут в очередной раз наткнулся на предупреждение от пхп инспекшена что юзайте "=== null" вместо is_null() и решил таки затестить, а есть ли реальный смысл в этом. в общем сделал массив из 10 000 элементов и вот что вышло: для версии 5.6 php - Testing with === 0.0006098747253418 Testing with is_null() 0.0013628005981445 получается === быстрее в два раза чем is_null для версии 7: Testing with === 0.00031208992004395 Testing with is_null() 0.00028300285339355 получается is_null() даже быстрее короче, в итоге что могу сказать... не заморачивайтесь, и смело можно юзать оба варианта :) в производительности не теряется ничего в обоих случаях, если вы используете 7 пхп и выше

Рекурсия, Предотвращение рекурсии, Управляющие трамплины

Довольно понятная, подробная и интересно написанная статья про рекурсии, как они работают, и как их избегать - читать на хабре

Функции высших порядков и монады для PHP`шников

кто хочет "поломать" себе мозг :) https://habrahabr.ru/post/309962/ - Функции высших порядков и монады для PHP`шников

Послевкусие экосистемы Ruby (on Rails) или "мы любим ненавидеть PHP"

От переводчика: Если вы PHP разработчик и поглядываете в сторону Ruby (on Rails), или же наоборот, вы Ruby разработчик и подумываете перейти на темную сторону PHP, то я думаю вам понравится этот перевод статьи " Ruby (on Rails) ecosystem bittersweet or «we like to hate PHP» ". Резюме: Я хочу представить некоторые факты, а также и личный опыт, в доказательство того, что PHP это более жизнеспособное, конкурентное и слабосвязанное сообщество, чем экосистема Ruby. Я имею ввиду: производительность, синтаксис, аспекты кодинга, сообщество и поддержка инструментария. Если вы хотите пропустить большую часть всей этой пустой тирады – то сразу же листайте до заголовка: “Главная часть начинается здесь...” Но я все же должен сказать это...

Предлагают ввести новый знак в PHP

Человек предлагает новый синтаксический знак <?~ $value ?> для вывода переменной с обработкой htmspecialchars и опцией ENT_QUOTES Вот статья -  https://habrahabr.ru/post/304162/ Как по мне вполне сомнительной полезности фича... 

Ruby on Rails vs PHP

Наткнулся на хорошую статью о разнице между Ruby on Rails и PHP фреймворками. Возможно кому-то будет интересно:  http://stdout.in/en/post/ruby-ecosystem-bittersweet-or-we-like-to-hate-php Есть нюанс, она на английском. Но там очень он простой и понятный. Приятного чтения.