Posted by: xSicKxBot - 03-27-2022, 04:07 AM - Forum: Python
- No Replies
Python os.walk() – A Simple Illustrated Guide
According to the Python version3.10.3 official doc, the os module provides built-in miscellaneous operating system interfaces. We can achieve many operating system dependent functionalities through it. One of the functionalities is to generate the file names in a directory tree through os.walk().
If it sounds great to you, please continue reading, and you will fully understand os.walk through Python code snippets and vivid visualization.
In this article, I will first introduce the usage of os.walk and then address three top questions about os.walk, including passing a file’s filepath to os.walk, os.walk vs. os.listdir, and os.walk recursive.
top: accepts a directory(or file) path string that you want to use as the root to generate filenames.
2. Optional parameters:
topdown: accepts a boolean value, default=True. If True or not specified, directories are scanned from top-down. Otherwise, directories are scanned from the bottom-up. If you are still confused about this topdown parameter like I first get to know os.walk, I have a nicely visualization in the example below.
onerror: accepts a function with one argument, default=None. It can report the error to continue with the walk, or raise the exception to abort the walk.
followlinks: accepts a boolean value, default=False. If True, we visit directories pointed to by symlinks, on systems that support them.
Tip: Generally, you only need to use the first two parameters in bold format.
Output
Yields 3-tuples (dirpath, dirnames, filenames) for each directory in the tree rooted at directory top (including top itself).
Example
I think the best way to comprehend os.walk is walking through an example.
Our example directory tree and its labels are:
By the way, the difference between a directory and a file is that a directory can contains many files like the above directory D contains 4.txt and 5.txt.
Back to our example, our goal is to
Generate filenames based on the root directory, learn_os_walk
Understand the difference between topdown=True and topdown=False
To use the os.walk() method, we need to first import os module:
import os
Then we can pass the input parameters to the os.walk and generate filenames. The code snippet is:
a_directory_path = './learn_os_walk' def take_a_walk(fp, topdown_flag=True): print(f'\ntopdown_flag:{topdown_flag}\n') for pathname, subdirnames, subfilenames in os.walk(fp, topdown=topdown_flag): print(pathname) print(subdirnames) print(subfilenames) print('--------------------------------') print('What a walk!') # *Try to walk in a directory path
take_a_walk(a_directory_path)
# Output more than Just 'What a walk!'
# Also all the subdirnames and subfilenames in each file tree level.
# BTW if you want to look through all files in a directory, you can add
# another for subfilename in subfilenames loop inside.
The above code has a function take_a_walk to use os.walk along with a for loop. This is the most often usage of os.walk so that you can get every file level and filenames from the root directory iteratively.
For those with advanced knowledge in Python’s generator, you would probably have already figured out that os.walk actually gives you a generator to yield next and next and next 3-tuple……
Back in this code, we set a True flag for the topdown argument. Visually, the topdown search way is like the orange arrow in the picture below:
And if we run the above code, we can the below result:
If we set the topdown to be False, we are walking the directory tree from its bottom directory D like this:
The corresponding code snippet is:
a_directory_path = './learn_os_walk' def take_a_walk(fp, topdown_flag=False): print(f'\ntopdown_flag:{topdown_flag}\n') for pathname, subdirnames, subfilenames in os.walk(fp, topdown=topdown_flag): print(pathname) print(subdirnames) print(subfilenames) print('--------------------------------') print('What a walk!') # *Try to walk in a directory path
take_a_walk(a_directory_path)
# Output more than Just 'What a walk!'
# Also all the subdirnames and subfilenames in each file tree level.
# BTW if you want to look through all files in a directory, you can add
# another for subfilename in subfilenames loop inside.
And if we run the above code, we can the below result:
Now, I hope you understand how to use os.walk and the difference between topdown=True and topdown=False.
Here’s the full code for this example:
__author__ = 'Anqi Wu' import os a_directory_path = './learn_os_walk'
a_file_path = './learn_os_walk.py' # same as a_file_path = __file__ def take_a_walk(fp, topdown_flag=True): print(f'\ntopdown_flag:{topdown_flag}\n') for pathname, subdirnames, subfilenames in os.walk(fp, topdown=topdown_flag): print(pathname) print(subdirnames) print(subfilenames) print('--------------------------------') print('What a walk!') # *Try to walk in a file path
take_a_walk(a_file_path)
# Output Just 'What a walk!'
# Because there are neither subdirnames nor subfilenames in a single file !
# It is like:
# for i in []:
# print('hi!') # We are not going to execute this line. # *Try to walk in a directory path
take_a_walk(a_directory_path)
# Output more than Just 'What a walk!'
# Also all the subdirnames and subfilenames in each file tree level.
# BTW if you want to look through all files in a directory, you can add
# another for subfilename in subfilenames loop inside. # *Try to list all files and directories in a directory path
print('\n')
print(os.listdir(a_directory_path))
print('\n')
How to Pass a File’s filepath to os.walk?
Of course, you might wonder what will happen if we pass a file’s filepath, maybe a Python module filepath string like './learn_os_walk.py' to the os.walk function.
This is exactly a point I was thinking when I started using this method. The simple answer is that it will not execute your codes under the for loop.
For example, if you run a code in our learn_os_walk.py like this:
import os a_file_path = './learn_os_walk.py' # same as a_file_path = __file__ def take_a_walk(fp, topdown_flag=False): print(f'\ntopdown_flag:{topdown_flag}\n') for pathname, subdirnames, subfilenames in os.walk(fp, topdown=topdown_flag): print(pathname) print(subdirnames) print(subfilenames) print('--------------------------------') print('What a walk!') # *Try to walk in a file path
take_a_walk(a_file_path)
The only output would be like this:
Why is that?
Because there are neither subdirnames nor subfilenames in a single file! It is like you are writing the below code:
for i in []: print('hi!')
And you will not get any 'hi' output because there is no element in an empty list.
Now, I hope you understand why the official doc tells us to pass a path to a directory instead of a file’s filepath
os.walk vs os.listdir — When to Use Each?
A top question of programmers concerns the difference between os.walk vs os.listdir.
The simple answer is:
The os.listdir() method returns a list of every file and folder in a directory. The os.walk() method returns a list of every file in an entire file tree.
Well, if you feel a little bit uncertain, we can then use code examples to help us understand better!
We will stick to our same example directory tree as below:
In this case, if we call os.listdir() method and pass the directory path of learn_os_walk to it like the code below:
import os a_directory_path = './learn_os_walk' # *Try to list all files and directories in a directory path
print('\n')
print(os.listdir(a_directory_path))
print('\n')
And we will get an output like:
That’s it! Only the first layer of this entire directory tree is included. Or I should say that the os.listdir() cares only about what is directly in the root directory instead of searching through the entire directory tree like we see before in the os.walk example.
Summary
Summary: If you want to get a list of all filenames and directory names within a root directory, go with the os.listdir() method. If you want to iterate over an entire directory tree, you should consider os.walk() method.
Now, I hope you understand when to use os.listdir and when to use os.walk
os.walk() Recursive — How to traverse a Directory Tree?
Our last question with os.walk is about how to literally iterate over the entire directory tree.
Concretely, we have some small goals for our next example:
Iterate over all files within a directory tree
Iterate over all directories within a directory tree
All examples below are still based on our old friend, the example directory tree:
Iterate over all files within a directory tree
First, let’s head over iterating over all files within a directory tree. This can be achieved by a nested for loop in Python.
The potential application could be some sanity checks or number counts for all files within one folder. How about counting the number of .txt files within one folder? Let’s do it!
The code for this application is:
import os a_directory_path = './learn_os_walk'
total_file = 0 for pathname, subdirnames, subfilenames in os.walk(a_directory_path): for subfilename in subfilenames: if subfilename.endswith('.txt'): total_file += 1
print(f'\n{total_file}\n')
As you can see, we use another for loop to iterate over subfilenames to get evey file within a directory tree. The output is 7 and is correct according to our example directory tree.
Iterate over all directories within a directory tree
Last, we can also iterate over all directories within a directory tree. This can be achieved by a nested for loop in Python.
The potential application could be also be some sanity checks or number counts for all directories within one folder. For our example, let’s check if all directories contains __init__.py file and add an empty __init__.py file if not.
Idea: The __init__.py file signifies whether the entire directory is a Python package or not.
The code for this application is:
import os a_directory_path = './learn_os_walk' for pathname, subdirnames, subfilenames in os.walk(a_directory_path): for subdirname in subdirnames: init_filepath = os.path.join(pathname, subdirname, '__init__.py') if not os.path.exists(init_filepath): print(f'Create a new empty [{init_filepath}] file.') with open(init_filepath, 'w') as f: pass
As you can see, we use another for loop to iterate over subdirnames to get evey directory within a directory tree.
Before the execution, our directory tree under the take_a_walk function mentioned before looks like this:
After the execution, we can take a walk along the directory tree again and we get result like:
Hooray! We successfully iterate every directory within a directory tree and complete the __init__.py sanity check.
In summary, you can use os.walk recursively traverse every file or directory within a directory tree through a nested for loop.
Conclusion
That’s it for our os.walk() article!
We learned about its syntax, IO relationship, and difference between os.walk and os.listdir.
We also worked on real usage examples, ranging from changing the search direction through topdown parameter, .txt file number count, and __init__.py sanity check.
Hope you enjoy all this and happy coding!
About the Author
Anqi Wu is an aspiring Data Scientist and self-employed Technical Consultant. She is an incoming student for a Master’s program in Data Science and builds her technical consultant profile on Upwork.
Anqi is passionate about machine learning, statistics, data mining, programming, and many other data science related fields. During her undergraduate years, she has proven her expertise, including multiple winning and top placements in mathematical modeling contests. She loves supporting and enabling data-driven decision-making, developing data services, and teaching.
Here is a link to the author’s personal website: https://www.anqiwu.one/. She uploads data science blogs weekly there to document her data science learning and practicing for the past week, along with some best learning resources and inspirational thoughts.
With Java 11 around the corner, and release candidate builds available at http://jdk.java.net/11 , it’s time to look back at the effect the new release cadence has had on adoption of new releases. Changing the Pace of Change New Java releases used to take quite a while to get adopted by developers. ...
Sendmail in PHP is possible with just single line of code. PHP contains built-in mail functions to send mail.
There are reasons why I am feeling embraced with this PHP feature. Because I write lot of code for sending mails regularly. PHP really saves our time with its built-ins.
Quick Example
<?php
mail('recipient@domain.com', 'Mail Subject', 'Mail test content'); ?>
In this tutorial, we will see how to add code to sendmail in PHP. We will see several examples in this to enrich the features with more support.
The below list examples we are going to see below. It will cover basic to full-fledged support to sendmail in PHP.
The PHP mail() is to sendmail from an application. Let’s see the PHP configurations required to make the mail() function work. Also, we will see the common syntax and parameters of this PHP function below.
$recipient_email One or more comma-separated value that is the target mail addresses. The sample format of the values are,
name@domain.com
Name <name@domain.com>
name@domain.com, name2.domain.com
Name <name@domain.com>, Name2 <name2@domain.com>
$subject Mail subject. It should satisfy RFC 2047.
$message Mail content body. It uses \r\n for passing a multi-line text. It has a character limit of 70 for a line. It accepts various content types depends on the specification in the extra header.
$headers This is an extra string or array append to the mail header. Use to pass the array of specifications like content-type, charset and more. It’s an optional parameter. It uses \r\n to append multiple headers. The header array contains key-value pair to specify header name and specification respectively.
$additional_params This is also optional. It is to pass extra flags like envelope sender address with a command-line option.
Return Values
This function returns boolean true or false based on the sent status of the mail. By receiving boolean true that doesn’t mean the mail was sent successfully. Rather, it only represents that the mail sending request is submitted to the server.
PHP sendmail – configurations
We have to configure some directives to make the mail script work in your environment.
Locate your php.ini file and set the mail function attributes. The below image shows the PHP configuration of the mail function.
Set the mail server configuration and the sendmail path with this php.ini section. Then restart the webserver and ensure that the settings are enabled via phpinfo().
Examples to Sendmail in PHP
Sendmail in PHP to send plaintext content
This is a short example of sending plain text content via PHP Script. It sets the mail subject, message and recipient email parameter to sendemail in PHP.
This program print response text based on the boolean returned by the mail() function.
sendmail-with-plain-text.php
<?php
$to = 'recipient@email.com';
$subject = 'Mail sent from sendmail PHP script';
$message = 'Text content from sendmail code.';
// Sendmail in PHP using mail()
if (mail($to, $subject, $message,)) { echo 'Mail sent successfully.';
} else { echo 'Unable to send mail. Please try again.';
}
?>
PHP Sendmail code to send HTML content
Like the above example, this program also uses the PHP mail() function to send emails. It passes HTML content to the mail function.
For sending HTML content, it sets the content type and other header values with the mail header.
php-mail-with-html-content.php
<?php
$to = 'recipient@email.com'; $subject = 'Mail sent from sendmail PHP script'; $from = 'test@testmail.com';
$headers = "From: $from";
$headers .= "MIME-Version: 1.0\r\n";
$headers .= "Content-Type: text/html; charset=UTF-8\r\n"; $message = '<p><strong>Sendmail in PHP with HTML content. </strong></p>'; if (mail($to, $subject, $message, $headers)) { echo 'Mail sent successfully.';
} else { echo 'Unable to send mail. Please try again.';
}
?>
Sendmail in PHP to attach files
This program attaches a text file with the email content. It reads a source file using PHP file_get_contents(). It encodes the file content and prepares a mail header to attach a file.
It sets content-type, encoding with the message body to make it work. This script uses the optional $header variable on executing sendmail in PHP.
Instead of static values, we can also pass user-entered values to the PHP sendmail. An HTML form can get the values from the user to send mail. We have already seen how to send a contact email via the form.
This example shows a form that collects name, from-email and message from the user. It posts the form data to the PHP on the submit action.
The PHP reads the form data and uses them to prepare mail sending request parameters. It prepares the header with the ‘from’ email. It sets the mail body with the message entered by the user.
All the form fields are mandatory and the validation is done by the browser’s default feature.
PHP mail() function has some limitation. To have a full-fledge functionality to sendmail in PHP, I prefer to use the PHPmailer library.
This library is one of the best that provides advanced mailing utilities. We have seen examples already to sendmail in PHP using PHPMailer via SMTP. If you are searching for the code to sendmail using OAuth token, the linked article has an example.
This example uses a minimal script to sendmail in PHP with PHPMailer via SMTP. It loads the PHPMailer library to create and set the mail object.
The mail object is used to configure the mail parameters. Then it invokes the send() method of the PHPMailer class to send mail.
Download PHPMailer from Github and put it into the vendor of this example directory. Replace the SMTP configurations in the below script to make this mail script working.
sendmail-in-php-via-smtp.php
<?php
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\SMTP;
use PHPMailer\PHPMailer\Exception; require_once __DIR__ . '/vendor/phpmailer/phpmailer/src/Exception.php';
require_once __DIR__ . '/vendor/phpmailer/phpmailer/src/PHPMailer.php';
require_once __DIR__ . '/vendor/phpmailer/phpmailer/src/SMTP.php'; $mail = new PHPMailer(true);
$mail->SMTPDebug = 0;
$mail->isSMTP();
$mail->Host = 'smtp.gmail.com';
$mail->SMTPAuth = true;
$mail->Username = "";
$mail->Password = "";
$mail->SMTPSecure = "ssl";
$mail->Port = 465; $mail->From = "test@testmail.com";
$mail->FromName = "Full Name"; $mail->addAddress("recipient@email.com", "recipient name"); $mail->isHTML(true); $mail->Subject = "Mail sent from php send mail script.";
$mail->Body = "<i>Text content from send mail.</i>";
$mail->AltBody = "This is the plain text version of the email content"; try { $mail->send(); echo "Message has been sent successfully";
} catch (Exception $e) { echo "Mailer Error: " . $mail->ErrorInfo;
}
?>
Related function to sendmail in PHP
The PHP provides alternate mail functions to sendmail. Those are listed below.
mb_send_mail() – It sends encoded mail based on the language configured with mb_language() setting.
imap_mail() – It allows to sendmail in PHP with correct handling of CC, BCC recipients.
Conclusion
The mail sending examples above provides code to sendemail in PHP. It supports sending various types of content, file attachments in the mail.
The elaboration on PHP in-built mail() function highlights the power of this function.
Hope this article will be helpful to learn more about how to sendmail in PHP. Download
This is a recurring promotion, making it the second time being given away on the Epic Store (Dec 17th 2020). The game is free to keep until Mar 17th 2022 - 16:00 UTC.
Next week's freebie: In Sound Mind
We are welcoming everyone to join our discord[discord.gg]. We are more active there on finding giveaways, small or large, and there are daily raffles you can participate.
The treacherous wizard Thoth-Amon has devised a plan to resurrect the ancient evil that is Xaltotun. If he succeeds, he will condemn the world to an eternity of darkness and enslavement. Only you can stop him, but in order to do so you must use all your cunning. All your guile. You must summon all your courage and swordsmanship. You must Chop Chop!
Conan Chop Chop is the most epic and realistic stick figure game ever to be set in the world of Conan the Barbarian, thus there will be an excessive amount of gore and flying limbs. Be warned that this may in turn lead to uncontrollable outbursts of joy and/or profanities, usually depending on which end of the sword you are on.
1-4 players
Play solo for the ultimate thrill of a roguelike or have your buddies along with you in online or couch co-op mode.
Become Conan or someone else!
All brawns, no brain? No worries! Choose between a diverse cast of badass warrior gods, and add weapons and items to match your style!
Embark on quests of pure epicness!
You are about to save the world! The merchants are still going to charge you for their wares, and some townsfolk may even pester you with tasks of their own. But fear not, some of them will make it worth your while.
Explore in every direction!
Brave the shifting sands of Koth, explore the dark woods in Darkwood, move valiantly through the searing land of Hyperboria and see the icy world of Vanaheim. Conan® Chop Chop lets you explore to the left, right, up and down! A skilled player may even find himself jumping, dashing, or moving diagonally, resulting in the ultimate 3D experience.
Loot, loot and more loot!
Master the fine art of delicately bashing your enemies' heads in with a broom and turning them into chop suey with a bastard sword. Conan® Chop Chop contains a wide variety of different weapons, trinkets and legendary items, each suited to tailor any kind of violent playstyle you can think of.
Master astonishing combos!
Perform the breathtaking 360° spin-attack to crack skulls all around you. Dash forward with the speed of light. Swing your sword both longways and sideways in a game that will have you gasping for air as you struggle to grasp the pure awesomeness of your fighting moves.
Ruthless bosses!
Before facing Thoth-Amon, you must defeat bosses such as The Giant Sand Worm of Koth and The Frost Giant of Vanaheim, neither of which are particularly sympathetic to your cause. Instead they will attempt to destroy you with killer moves like Lava Reflux, Tail Whip and Loogie Glob.
Infinite replayability!
Completely random maps and tons of weapons and abilities to try out ensure that every new game will be a whole new experience. You are bound to die more than once, but you can unlock new weapons that will be available for your next play-through.
Decoupling microservices with Apache Camel and Debezium
The rise of microservices-oriented architecture brought us new development paradigms and mantras about independent development and decoupling. In such a scenario, we have to deal with a situation where we aim for independence, but we still need to react to state changes in different enterprise domains.
I’ll use a simple and typical example in order to show what we’re talking about. Imagine the development of two independent microservices: Order and User. We designed them to expose a REST interface and to each use a separate database, as shown in Figure 1:
Figure 1: Order and User microservices.
We must notify the User domain about any change happening in the Order domain. To do this in the example, we need to update the order_list. For this reason, we’ve modeled the User REST service with addOrder and deleteOrder operations.
Solution 1: Queue decoupling
The first solution to consider is adding a queue between the services. Order will publish events that User will eventually process, as shown in Figure 2:
Figure 2: Decoupling with a queue.
This is a fair design. However, if you don’t use the right middleware you will mix a lot of infrastructure code into your domain logic. Now that you have queues, you must develop producer and consumer logic. You also have to take care of transactions. The problem is to make sure that every event ends up correctly in both the Order database and in the queue.
Solution 2: Change data capture decoupling
Let me introduce an alternative solution that handles all of that work without your touching any line of your microservices code. I’ll use Debezium and Apache Camel to capture data changes on Order and trigger certain actions on User. Debezium is a log-based data change capture middleware. Camel is an integration framework that simplifies the integration between a source (Order) and a destination (User), as shown in Figure 3:
Figure 3: Decoupling with Debezium and Camel.
Debezium is in charge of capturing any data change happening in the Order domain and publishing it to a topic. Then a Camel consumer can pick that event and make a REST call to the User API to perform the necessary action expected by its domain (in our simple case, update the list).
Decoupling with Debezium and Camel
I’ve prepared a simple demo with all of the components we need to run the example above. You can find this demo in this GitHub repo. The only part we need to develop is represented by the following source code:
Apache Camel has a Debezium component that can hook up a MySQL database and use Debezium embedded engine. The source endpoint configuration provides the parameters needed by Debezium to note any change happening in the debezium._order table. Debezium streams the events according to a JSON-defined format, so you know what kind of information to expect. For each event, you will get the information as it was before and after the event occurs, plus a few useful pieces of meta-information.
Thanks to Camel’s content-based router, we can either call the addOrderUsingPOST or deleteOrderUsingDELETE operation. You only have to develop a message translator that can convert the message coming from Debezium:
public class AfterStructToOrderTranslator implements Processor { private static final String EXPECTED_BODY_FORMAT = "{\"userId\":%d,\"orderId\":%d}"; public void process(Exchange exchange) throws Exception { final Map value = exchange.getMessage().getBody(Map.class); // Convert and set body int userId = (int) value.get("user_id"); int orderId = (int) value.get("order_id"); exchange.getIn().setHeader("userId", userId); exchange.getIn().setHeader("orderId", orderId); exchange.getIn().setBody(String.format(EXPECTED_BODY_FORMAT, userId, orderId)); } }
Notice that we did not touch any of the base code for Order or User. Now, turn off the Debezium process to simulate downtime. You will see that it can recover all events as soon as it turns back on!
The example illustrated here uses Debezium’s embedded mode. For more consistent solutions, consider using the Kafka connect mode instead, or tuning the embedded engine accordingly.
Java Mission Control - Now serving OpenJDK binaries too!
Oracle plans to make the open source JDK Mission Control (JMC) technology available as a separate download to serve both OpenJDK and Oracle JDK users. Here are some of the reasons why: To make it available to all Java users Java Flight Recorder (JFR) is open source now. JFR will be included in both ...
Posted by: xSicKxBot - 03-26-2022, 03:53 AM - Forum: Python
- No Replies
Agile Software Development with Scrum
Abstract: Is Agile software development with Scrum effective for businesses and tech companies? Here are the benefits of Scrum methodology and everything you should know about it!
In the field of software development, agile software development with Scrum is one of the most popular methodologies. Flexible and low-cost, Agile Scrum is a powerful project management framework to increase teamwork and break down tasks, maximizing quality results.
Already in 2018, 94% of developers were using or used Scrum in their agile practice – of which, 78% use it with other frameworks, and 16% only work with it.
But what is Scrum in Agile methodology? Here is an overview of the Scrum framework, including methods, benefits, and practices to know.
What Is Scrum?
Scrum is an Agile lifecycle subset method. The lightweight framework focuses on maximizing productivity while ensuring teamwork. Scrum teams work in collaborative environments with effective communication processes.
Scrum methodology enables last-minute adjustments and rapidly-changing requirements, increasing deliverables qualities and market trends compared to traditional waterfall processes. It’s an effective and low-cost solution for startups and small teams of 7-9 people.
Benefits of Agile Software Development With Scrum
The main benefit of Scrum methodologies is flexibility. The team can adjust their workflow on the go based on market trends and users’ needs. Because of its nature, this methodology isn’t the most efficient option for plan-driven approaches or large and complex projects. However, it’s an efficient and valuable solution for startups and team environments, facilitating collaborative tasks and innovative solutions to improve products and services.
Here are the core benefits of Agile software development with Scrum:
Flexible and Adaptable: Scrum framework is one of the most effective solutions for new projects and startups. This Agile development methodology allows changes and edits on the go, without effective output. For this reason, it’s one of the most effective solutions for projects for companies in analyzing their customers’ requirements or improving their services over time.
Time to Market: Scrum Agile methodologies require a short setup time, ensuring a fast and quality delivery to break into the market with new products and services.
Lower Costs: Agile Scrum reduces a company’s costs because of automated documentation and control processes and increased productivity in the workflow.
Transparency: Scrum methodology increases transparency between clients and the company. Any minor change is visible to all members, enforcing trust among consumers.
Increase productivity: Agile Scrum provides a set system for deadlines and performance indicators. In addition, team members get rewards when meeting KPIs and quality checks, increasing team motivation and productivity.
Feedback system: This methodology requires daily check-in and feedback for progress reports, ensuring a smoother and more efficient workflow in the long run.
Scrum Methodologies and Processes
As a part of Agile development methodologies, the Scrum framework consist of iterative processes to ensure teamwork and communication during the process.
To put it simply, Scrum methods break the waterfall process delivery into smaller cycles. As a result, product teams and the end-customer can review the working software to ensure quality requirements at each stage – for the business and clients alike.
In short, Agile Scrum method consists of Scrum roles, events, and artifacts:
Let’s have a closer look at the meaning and function elements in Agile software development with Scrum.
Agile Software Development With Scrum: Roles
In the Scrum framework, team members work to improve the software quality based on the product’s characteristics and business requirements.
In general, a Scrum team consists of three leading roles:
Scrum Master: This role guides the team in complying with rules and method processes. A Scrum master monitor bugs and development process to reduce obstacles and maximize the ROI with the Product Owner. In addition, this role takes care of Scrum updates while coaching, mentoring, and training the team for better results.
Product owner (PO): The Product owner represents stakeholders and customers using the software. The focus is on the business requirements and the project ROI for this role. In short, they support the dev team in translating the project vision into a compelling product and service.
Team: The team consists of professionals combining their tech knowledge to improve and implement the product during several cycles and stages.
Agile Software Development With Scrum: Events
Events in Scrum are a series of cycles (usually 2/3 weeks). Called Sprints, these cycles are a timebox to complete a set amount of tasks. The Scrum team combines multiple Sprints before the final Release, when the software enters the market and the product arrives at customers.
Usually, the Product Owner breaks down the whole product functionality into smaller Epics or User Stories features. Prioritizing different stories helps the team monitor and test demos and prototypes and ensure the product’s complete functionality.
Any Scrum event aims to simplify the adaptation and implementation of the process, the product, progress, or relationships.
Here are the main Sprint in Agile software development with Scrum:
Sprint is the basic work unit for a Scrum team. It is the main feature that marks the difference between Scrum and other models for agile development.
Sprint Planning aims to define what and how it will be done during the current Sprint. Meeting at the beginning of each Sprint, the Scrum Master and team plan and determine how to approach the project coming from the Product Backlog stages and deadlines.
Daily Scrum concerns the project evaluation and trend until the end of the Sprint. In addition, the team synchronizes activities and creates a plan for the following 24 hours.
Sprint Review aims to provide an overview of what has been done about the product backlog for future deliveries. At the end of each Sprint, team members report obstacles and implementation to the client.
During the Sprint Retrospective, the team reviews goals analyzing positive and negative input. This stage aims to identify improvement steps and generate an effective plan for the next cycle.
Agile Software Development With Scrum: Artifacts
Finally, Scrum Artifacts ensures transparency decision making and key information between customers and stakeholders:
Product Backlog (PB): It is the process of listing what a product needs to satisfy potential customers. The Product Owner prioritizes what is important for the business, indicating what should be done to achieve requested quality standards for the product.
Sprint Backlog (SB): As a subset of product backlog items, the team selects which type of tasks to perform during the Sprint, establishing the duration of the cycle and final goals on a shared Scrum board.
Increment: This Scrum artifact sums up tasks, user cases and stories, product backlogs, and any relevant element, and it makes them visible to software end-users.
Conclusion
Agile software development with Scrum ensures a transparent and efficient workflow in mid-sized development teams. This framework allows breaking the whole development cycle in smaller breaks, simplifying the implementation and debugging process. Especially for startups and growing teams, it’s one of the best methodologies to improve development processes and ensure high-quality outcomes, especially for startups and growing teams.
This is a guest post contributed by:
Author’s Bio
Costanza Tagliaferri is a Writer and Content Marketer at DistantJob. She has covered a wide range of topics. Now, she is focussing on technology, traveling, and remote work.
The PHP object to array conversion makes it easy to access data from the object bundle. Most of the API outputs object as a response.
Some APIs may return a complex object structure. For example, a mixture of objects and arrays bundled with a response. At that time, the object to array conversion process will simplify the data parsing.
This quick example performs a PHP object to array conversion in a single step. It creates an object bundle and sets the properties.
It uses JSON encode() decode() function for the conversion. The json_decode() supplies boolean true to get the array output.
Quick example
PHP object to array conversion in a line using json_decode
After decoding, the output array is printed to the browser. The below screenshot shows the output of this program.
Different ways of converting a PHP object to array
When converting an object to array, the object property ‘name:value’ pairs will form an associative array.
If an object contains unassigned properties then it will return an array with numerical keys.
There are two ways to achieve a PHP object to array conversion.
Typecasting object into an array.
Encoding and decoding object properties into an array of elements.
Typecasting is a straightforward method to convert the type of input data. The second method applies json_decode() on the given object. It supplied boolean true as a second parameter to get the output in an array format.
This article includes examples of using both of the above methods to perform the object to array conversion.
PHP object to array using typecasting
This is an alternate method to convert an object type into an array. The below program uses the same input object.
It replaces the JSON encode decode via conversion with the typecasting statement. The output will be the same as we have seen above.
The PHP typecasting syntax is shown below. It prepends the target data type enclosed with parenthesis.
This example uses an input object with depth = 3. It adds more properties at a nested level at different depths. The hierarchical object bundle is set as the input for the conversion process.
This program defines a custom function to convert a PHP object to array. It performs the conversion recursively on each level of the input object.
This is the output of the recursive PHP object to the array conversion program above.
Convert PHP class object into array
This example constructs a PHP class object bundle. The class constructor sets the properties of the object during the instantiation.
Then, the Student class instance is encoded to prepare object type data. The json_encode() function prepares the JSON object to supply it for decoding. The json_decode() converts the PHP object to array.
It is good programming practice to check the data availability before processing. This example applies the is_object verification before converting a PHP object to an array.
This method verifies if the input is an object. PHP includes exclusive functions to verify data availability and its type. Example isset(), empty(), is_array() etc.
The below program defines a class with private and protected properties. The PHP code instantiates the class and creates an object bundle.
It uses both the typecasting and decoding methods to convert the object into an array.
When using typecasting, the output array index of the private property contains the class name prefix. After conversion, the array index has a * prefix for the protected properties.
converting-private-protected-object.php
<?php
class Student
{ public $name; private $id; protected $email; public function __construct() { $this->name ="William"; $this->id = 5678; $this->email = "william@gmail.com"; }
} print "<pre>";
$student = new Student;
$result = json_encode($student);
$output1 = json_decode($result, true);
print "<br/>Using JSON decode:<br/>";
print_r($output1); $output2 = new Student;
print "<br/><br/>Using Type casting:<br/>";
print_r( (array) $output2 );
?>
This output screenshot shows the difference in the array index. Those are created from the private and protected properties of the class instance.
Accessing object properties with numeric keys
This code includes an associative array of student details. It also contains values with numeric keys.
When converting this array into an object, the associative array keys are used to access the object property values. There are exceptions to access properties if it doesn’t have a name.
The below code shows how to access objects with numeric keys. The key is enclosed by curly brackets to get the value.
We have seen the different ways of converting a PHP object to an array. The basic PHP typecasting has achieved an object conversion except for few special cases.
The PHP JSON encode decode process made the conversion with one line code. It accepts class objects and converts their properties into an array list.
The custom function processes recursive object to array conversion. It is to handle complex objects with mixed objects or arrays as its child elements. download