Back (Current repo: scraps)

random scraps and notes that are useful to me
To clone this repository:
git clone https://git.viktor1993.net/scraps.git
Log | Download | Files | Refs

commit 0434ffdf59daea73b55040fe5bda70caa8194545
parent 22fadb2e3fcbe9f714f92d138c453302cb86c875
Author: root <root>
Date:   Sun, 20 Apr 2025 23:09:06 +0200

add few new files

Diffstat:
Aphp/call_private_function_outside_class.php | 43+++++++++++++++++++++++++++++++++++++++++++
Asql/snippets/insert_range_of_integers.sql | 8++++++++
Asql/snippets/trim_table_from_old_data.sql | 22++++++++++++++++++++++
3 files changed, 73 insertions(+), 0 deletions(-)

diff --git a/php/call_private_function_outside_class.php b/php/call_private_function_outside_class.php @@ -0,0 +1,43 @@ +<?php + +/* + * How to access private properties and/or methods from outside the class <- without changing the class itself! + * Why? Sometimes you might be given a framework where changing the class isn't ideal, because a version update + * will overwrite your customizations of said class. + * + * How? Using Closure::call() temporarily binds $this to an instance of an object, giving the closure a + * privileged access to the private members. + * + */ + +class Foo { + private $bar = "Foo and Bar"; + private function add($a, $b) { + $this->c = $a + $b; + return $this->c; + //return $a + $b; + } +} + +$foo = new Foo; + +// Single variable example +// This should not work! +$getFooBar = function() { + return $this->bar; +}; + +// now $this is bound to $foo and PHP lets the closure access the private stuff +// because now it treats it as if it were inside the class at that moment, but it isn't +echo $getFooBar->call($foo); // Prints Foo and Bar +echo PHP_EOL; + +// Function call with parameters example +$doAdd = function() { + return $this->add(...func_get_args()); +}; + +echo $doAdd->call($foo, 10, 5); +echo PHP_EOL; + +?> diff --git a/sql/snippets/insert_range_of_integers.sql b/sql/snippets/insert_range_of_integers.sql @@ -0,0 +1,8 @@ +INSERT INTO some_table +SELECT @ROW := @ROW + 1 AS ROW, 'whatever', NOW(), NOW() +FROM some_big_table t + JOIN (SELECT @ROW := 1000) t2 +LIMIT 100; +--insert values 1000 to 1100. As long as some_big_table has at least that many rows, this method will work. + +-- Assume some_table has columns id INT, name VARCHAR(100), stamp_created DATETIME, stamp_modified DATETIME diff --git a/sql/snippets/trim_table_from_old_data.sql b/sql/snippets/trim_table_from_old_data.sql @@ -0,0 +1,22 @@ +-- add to crontab so that it can clean up from time to time +DROP procedure IF EXISTS `sp_super_delete_table_x`; + +DELIMITER $$ + +CREATE PROCEDURE `sp_super_delete_table_x`() +MODIFIES SQL DATA +BEGIN + +REPEAT + DO sleep(2); + DELETE FROM `some_schema`.`x` + WHERE date_entered < DATE_SUB(CURRENT_DATE(), INTERVAL 3 month) + ORDER BY date_entered + LIMIT 20000; -- or whatever makes sense + UNTIL row_count() = 0 +END REPEAT; + + +END $$ + +DELIMITER ;